perfect number problem

write a program asks the user for a positive integer value and then prints out all perfect numbers from 1 to that positive integer.
I have been trying for some time, i found a way to check if its a perfect number or not but could not find a way to prints out all perfect numbers from 1 to that positive integer. I am here so far.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,i=1,sum=0;
cout<<"Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
{

cout << i << " is a perfect number";
for(i=1;i<n;i--)

}
else
cout << i << " is not a perfect number";
return 0;
}
I would suggest starting again and following some logical steps.

-Declare an int to store the user value, an int for the running total and another int for incrementing loops. <- You already did this bit correctly in your code.
-Find all the factors, (excluding the number itself) of the user input number and total them. You will need a loop to do this, where the value in the loop should be incrementing and then being checked to see if it is a factor with the modulus operator % . The loop should run until n /2.
-Check to see if the total of factors and number are equal and output appropriate answer with if/else.
Last edited on
i looked at your code and it has many algorithmic mistakes

@Mats is right. the best thing you should do is a restart!. after you take a break of course.

have fun :D
Last edited on
made this one, i am able to find a perfect number but what to do about finding all other perfect numbers from 1 to that number..

#include<stdio.h>
int main(){
int n,i=1,sum=0;

printf("Enter a number: ");
scanf("%d",&n);

while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);

return 0;
}



didnt used the for loop in this one
Last edited on
Nevermind. figured it out. Thanks anyway.
Topic archived. No new replies allowed.