Perfect Number in C++

C++Server Side ProgrammingProgramming

Suppose we have to check whether a given number is perfect number or not. A number is said to be a Perfect Number when that is equal to the sum of all its positive divisors except itself. The number n will be in range 1^8.

So, if the input is like 28, then the output will be True, as its sum of divisors − 1 + 2 + 4 + 7+ 14 = 28.

To solve this, we will follow these steps −

As the numbers are in range 10^8, there are only few perfect numbers, if the given input is in that set, then answer will be true, otherwise false. The perfect numbers are 6, 28, 496, 8128 and 33550336.

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool checkPerfectNumber(int num) {
      set<int> set={6,28,496,8128,33550336};
      return set.find(num)!=set.end();
   }
};
main(){
   Solution ob;
   cout << (ob.checkPerfectNumber(28));
}

Input

28

Output

1
raja
Published on 10-Jun-2020 16:32:27
Advertisements