Check if a number can be expressed as sum two abundant numbers in C++

C++Server Side ProgrammingProgramming

Suppose we have a number. We have to express this as sum of two Abundant number, if yes, print the numbers, otherwise print -1. A number is said to be Abundant number is sum of all proper divisor of the number, denoted by sum(n) is greater than the value of number.

To solve this, we will store all abundant numbers into a set, and for given number n, run a loop for i = 1 to n, and check n and (n – i) are abundant or not.

Example

#include <iostream>
#include <set>
#define N 100005
using namespace std;
set<int> getAbundantSet() {
   set<int> abundant_set;
   for (int i = 1; i < N; i++) {
      int sum = 1;
      for (int j = 2; j * j <= i; j++) {
         if (i % j == 0) {
            sum += j;
            if (i / j != j)
            sum += i / j;
         }
      }
      if (sum > i)
         abundant_set.insert(i);
   }
   return abundant_set;
}
void representSumAbundant(int number){
   set<int> abundant_set = getAbundantSet();
   for (int i = 1; i <= number; i++) {
      if (abundant_set.count(i) && abundant_set.count(number - i)) {
         cout << i << " " << number - i;
         return;
      }
   }
   cout << -1;
}
int main() {
   int n = 30;
   representSumAbundant(n);
}

Output

12 18
raja
Published on 21-Oct-2019 10:06:23
Advertisements