perfect number is an integer that is equal to the sum of its factors. write down a c++ program that takes an integer x as an input and prints all perfect numbers from 1 to x.
#include <iostream>
#include <cctype>
using namespace std;
int perfectNumber(int n){
int i=1,sum=0;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
return 1;
else
return 0;
}
int main(){
int n;
cout << "Enter a number: ";
cin >> n;
for(int i=1; i<=n; i++){
if(perfectNumber(i)==1){
cout<<i<<endl;
}
}
return 0;
}
Comments
Leave a comment