What is a Perfect number:
Perfect Number is a number in which sum of all its positive divisors excluding that number is equals to the number.
For example: 6
Sum of divisors = 1+2+3 = 6
Here we will find perfect numbers between 1 and 500.
Program explanation:
- Take first number as 1.
- Use a while loop to generate numbers from 1 to 500 (where 500 is not included as we need the sum of the proper divisors of the number).
- Using an if statement check if the number divided by ‘i’ gives the remainder as 0 which is basically the proper divisor of the integer.
- Then the proper divisors of the number are added to the sum variable.
- If the sum of the proper divisors of the number is equal to the original number, the number is a Perfect number.
- The final result is printed.
C++ Program to find perfect numbers between 1 and 500:
#include<iostream>
using namespace std;
int main()
{
int i=1, u=1, sum=0;
while(i<=500)
{ // start of first loop.
while(u<=500)
{ //start of second loop.
if(u<i)
{
if(i%u==0 )
sum=sum+u;
} //End of if statement
u++;
} //End of second loop
if(sum==i)
{
cout<<i<<" is a perfect number."<<"\n";
}
i++;
u=1; sum=0;
} //End of First loop
return 0;
} //End of main
OUTPUT:
1 thought on “Program to find Perfect Number Program in C++”