C++ Program to check whether a number is Perfect Number or not

Program to check whether a number is Perfect Number or not

Here we will discuss how to check whether a number is Perfect number or not using C++ Programming language.

Perfect Number is a number in which the sum of the proper positive divisors of the number is equal to the number itself.

To check for Perfect Number find and add the divisors of the number and compare, if both are equal then it is a Perfect Number else it is not a Perfect Number.

For Example: 28

Sum of divisors = 1 + 2 + 4 + 7 + 14

   = 28

Program to check whether a number is a perfect number or not

Working

Let’s see how the code works:

  • User gives an input
  • Input is stored in an int type variable say num.
  • A Loop is started
    • Divisors of the number is found.
    • When a divisor is found it is added to sum , to calculate the sum of the divisors.
    • the loop will works until all the divisors are not added.
  • sum is compared with num
    • if both are equal then the number is a Perfect number
    • otherwise then number is not a Perfect Number

C++ Code

//C++ Program
//Perfect Number or not
#include<iostream>
using namespace std;
//main Program
int main ()
{
int div, num, sum=0;
cout << "Enter the number to check : ";
//user input
cin >> num;
//loop to find the sum of divisors
for(int i=1; i < num; i++)
{
div = num % i;
if(div == 0)
sum += i;
}
//checking for perfect number
if (sum == num)
cout<< num <<" is a perfect number.";
else
cout<< num <<" is not a perfect number.";
return 0;
}

Output

Enter the number to check : 28
28 is a perfect number.

Please Login/Signup to comment