C++ Program to Find Perfect Number

This C++ program is used to find the perfect number of a positive number and find its all positive divisors excluding that number.

For example: 6 is Perfect Number since divisor of 6 are 1, 2 and 3. Sum of its divisor is

1 + 2+ 3 =6

and 28 is also a Perfect Number

since 1+ 2 + 4 + 7 + 14= 28

Other perfect numbers: 496, 8128

#include <iostream> 
#include <cctype>
using namespace std; 

int main(){
    int n,i=1,sum=0;
    cout << "Enter a number: ";
    cin >> n;
    cout << i << " is a perfect number\n"; 
    cout << i << " is not a perfect number\n";

return 0;
Program Output:
6 is a perfect number

15 is not a perfect number

28 is a perfect number

496 is a perfect number

For Example, 6 is a perfect number since divisors of 6 are 1, 2, and 3, then sum of its divisor is 1 + 2 + 3 = 6. So, first of all, you have to include the iostream header file using the "include" preceding by # which tells that hat the header file needs to be process before compilation, hence named preprocessor directive. Again the ctype header file declares several functions which are helpful for testing and mapping characters. Now, for removing naming conflict you can use namespace statement within a program.

Now, the main() function is declared having return type as integer. Now you have to declare three integer type variables name - 'n', 'i' and sum and initialize 'i' as 1 and sum as 0. Now use the cout statement to display a message:
"Enter a number: ".

Then, the cin statement will fetch the value from the keyboard and initializes it to 'n'. Now you will implement a while loop which will check for iteration whether 'i' is greater than 'n' or not. If yes, then check whether n%i is equals to 0; If the for statement results as True, sum becomes sum+I and I gets incremented by 1. Now, outside the loop, it is checked when sum==n, prints "The given number is a perfect number" else not.

Scroll Back to Top