A perfect number is an integer that is equal to the sum of its factors. For example, 6 is a perfect number
as 6 = 3+2+1. Write down a program that takes an integer x as an input and prints all perfect numbers
from 1 to x.
SOLUTION CODE
#include <iostream>
using namespace std;
int main()
{
cout<<"Enter an integer to get the perfect numbers upto that point: ";
int my_integer;
cin>>my_integer;
//Now let the get the perfect numbers
cout<<"The following are perfect numbers between 1 and "<<my_integer<<endl;
for(int i = 2; i < my_integer; i++)
{
//declare a variable to store the sum of the integers
int sum = 0;
for(int j = 1; j<=((i/2)+1); j++)
{
if(i%j==0)
{
sum = sum + j;
}
}
if(sum==i)
{
cout<<i<<" ";
}
}
return 0;
}
SAMPLE PROGRAM CODE
Comments
Leave a comment