Program to find all perfect numbers upto n
An integer is said to be perfect number if its factors (including 1 but not number itself ) is sum to the number
Example:
6 is a perfect number as
6 = 1+2+3
Program:
/* cpp program to find perfect numbers upto n */
#include"iostream"
using namespace std;
int main()
{
int num, i, j, sum = 0;
do
{
cout<<"Enter a number: "; //get a number upto which perfect number is to be found
cin>>num;
if(num<1)
{
cout<<"Enter a valid positive integer."<<endl;
}
}while(num<1);
cout<<"Perfect numbers below "<<num<<" are:"<<endl;
for(i=1; i<=num; i++)
{
sum = 0;
for(j=1; j<i; j++)
{
if(i%j == 0)
{
sum = sum + j; //sum of factors of i
}
}
if(sum == i)
{
cout<<sum<<" = ";
for(j=1; j<sum; j++)
{
if(sum % j == 0)
{
cout<<j<<" ";
}
}
cout<<"\n";
}
}
}
Output:

Example:
6 is a perfect number as
6 = 1+2+3
Program:
/* cpp program to find perfect numbers upto n */
#include"iostream"
using namespace std;
int main()
{
int num, i, j, sum = 0;
do
{
cout<<"Enter a number: "; //get a number upto which perfect number is to be found
cin>>num;
if(num<1)
{
cout<<"Enter a valid positive integer."<<endl;
}
}while(num<1);
cout<<"Perfect numbers below "<<num<<" are:"<<endl;
for(i=1; i<=num; i++)
{
sum = 0;
for(j=1; j<i; j++)
{
if(i%j == 0)
{
sum = sum + j; //sum of factors of i
}
}
if(sum == i)
{
cout<<sum<<" = ";
for(j=1; j<sum; j++)
{
if(sum % j == 0)
{
cout<<j<<" ";
}
}
cout<<"\n";
}
}
}
Output:
Good example. I was searching for the same.
ReplyDeleteThanks.