C++ Program to Check Perfect Number

Last Updated:

What is Perfect Number?

A positive integer that is equal to the sum of its proper divisors.

For example, 6 is a perfect number
6 = 1 + 2 + 3
6 = 6

Tips: It is recommended to use our online Perfect Number calculator for better understanding.

Check Perfect Number

In the following example, we will check whether the given number (496) is a Perfect number or not.

Example

C++ Compiler
#include <iostream> using namespace std; int main() { int num = 496; int i = 1; int total = 0; for(i=1; i<num; i++) { if(num % i == 0) total += i; } if(total == num) cout << num << " is a perfect number"; else cout << num << " is not a perfect number"; return 0; }

Perfect Numbers between the Given Range

In the following example, we will find all the Perfect numbers between 1 and 1000.

Example

C++ Compiler
#include <iostream> using namespace std; int main() { int start = 1; int end = 1000; int i = 1; int total = 0; int flag = 0; cout << "Perfect numbers between " << start <<" and " << end << ":\n"; for(start=start; start<=end; start++) { for(i=1; i<start; i++) { if(start % i == 0) total += i; } if((total == start) && (start != 0)) { flag = 1; cout << start <<" "; } total = 0; } if(flag == 0) cout << "There in no perfect number between the given range"; return 0; }

Check Whether the Given Number is Perfect or Not

In the following example, we will check whether the given number is a Perfect Number or Not.

Example

C++ Compiler
#include <iostream> using namespace std; int main() { int num, i = 1; int total = 0; cout << "Enter a (int) number: "; cin >> num; for(i=1; i<num; i++) { if(num % i == 0) total += i; } if(total == num) cout << num << " is a perfect number"; else cout << num << " is not a perfect number"; return 0; }

Share this Page

Meet the Author