C++ Program To Check Perfect Number or Not
In mathematics, a perfect number is a positive integer that is
equal to the sum of its positive divisors, excluding the number itself.
For Example,
28 is a positive number that is completely divisible by 1, 2, 4, 7 and 14.
We know that the number is also divisible by itself but we will exclude it in the addition of divisors.
When we add these divisors (1 + 2 + 4 + 7 + 14 = 28), it produces 28, which is equal to the number that we have considered.
So, we can say that 28 is a perfect number.
you can use the following algorithm:
- Read the input number.
- Initialize a variable sum to 0.
- Iterate through all the numbers from 1 to number/2 (excluding number itself).
- For each iteration, check if the current number is a divisor of the input number.
- If the current number is a divisor, add it to the sum.
- After the loop, check if the sum is equal to the input number.
- If they are equal, the number is a Perfect Number; otherwise, it is not.
- Print the result.
This algorithm calculates the sum of the divisors of the input number and compares it with the input number to determine if it is a Perfect Number.
Here is an example implementation in C++Source Code
// C++ Program To Check Perfect Number
#include<iostream.h>
#include<conio.h>
void main()
{
int num , i , sum = 0 ;
cout<<"Enter a Number To Check : ";
cin>>num;
for( i=1; i<=num/2; i++ )
{
if(num%i==0)
{
cout<<i<<" ";
sum = sum + i ;
}
}
cout<<"\nSum of Factors of a Given number : "<<sum<<endl;
if(sum==num)
cout<<"It is a Perfect Number . ";
else
cout<<"It is Not a Perfect Number . ";
getch();
}
Output
Sample Input :
Enter a Number To Check : 28
Sample Output:
1 2 4 7 14
Sum of Factors of a Given Number : 28
It is a Perfect Number
Sample Input :
Enter a Number To Check : 10
Sample Output:
1 2 5
Sum of Factors of a Given Number : 8
It is Not a Perfect Number