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

perfect number

Algorithm:-

  1. User gives an input
  2. Input is stored in an int type variable say num.
  3. divisors of num can be found in range  1 to num
  4. Initialize sum to 0
  5. A Loop is traversed from i=1 to num
    1. check wether i is divisor of num or not using num%i==0.
      1. If i is divisor of num then update sum=sum+i.
    2. the loop will works until all the divisors are not added.
  6. sum is compared with num
    1. if both are equal then the number is a Perfect number
    2. otherwise then number is not a Perfect Number
Perfect Number or Not

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.