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.
#include<iostream>
using namespace std;
int perfect(int n){
int sum=0;
for(int i=1; i<n;i++){
if(n%i==0){
sum += i;
}
}
if(n==sum){
return 1;
}
else{
return 0;
}
}
int main(){
cout<<"Enter a number:\n";
int x;
cin>>x;
for(int i=1; i<=x; i++){
if(perfect(i)==1){
cout<<i<<endl;
}
}
}
Comments
Leave a comment