C++ Program to check whether a number is perfect number or not [DEVCPP/GCC]


PERFECT NUMBER

A positive number is said to be perfect number if it is equal to the sum of its divisors.

For example,
The divisors of 6 are 1,2 and 3 and 1+2+3 = 6. Thus 6 is a perfect number.
The divisors of 28 are 1,2,4,7 and 14 and 1+2+4+7+14 = 28. Thus 28 is a perfect number.

STEPS

1. Initialize a variable sum with 0.

2. Input the number(num) from the user.

3. Initialize a counter (i) with 1.

4. Check the divisibility of num with i.

5. If it is divisible then add i to sum.

6. Increment counter(i).

7. Repeat steps 4-6 until i<=(num/2).

8. If sum is equal to num, then it is a perfect number else not.

PROGRAM

//  Program to check whether given number is perfect number or not.

#include <iostream>

using namespace std;

int main()
{
        int num ,sum=0 ,i;

        cout<<"ENTER A NUMBER: ";
        cin>>num;

        for(i=1;i<=(num/2);i++)
       {
                if(num % i==0)
               {
                        sum = sum + i;
               }
       }

       cout<<endl;

        if(sum==num)
       {
                cout<<num<<" IS A PERFECT NUMBER";
        }
        else
        {
               cout<<num<<" IS NOT A PERFECT NUMBER";
        }
        return 0;
}

OUTPUT

C++ Program to check whether a number is perfect number or not with output


Share this

Related Posts

FIND US ON FACEBOOK!