Perfect numbers between 1 and 1000

user10198594 picture user10198594 · Aug 22, 2018 · Viewed 13.1k times · Source

I don't understand why this program doesn't give any output. I just can't see the bug. This is a program to find every perfect number between 1 and 1000. Please help me find the bug. Thanks.

#include <stdio.h>

int main(){
    int number=1, i, sum=0;

    while(number<=1000){

        for(i=1; i<number; i++){
            if(number%i==0){
                sum+=i;
            }
        }

        if(sum==number){
            printf("%d is perfect\n", numero);
        }
        number++;
    }

    return 0;   
}

Answer

Laurent H. picture Laurent H. · Aug 22, 2018

As already said, you have to reset the sum to zero at the beginning of the loop.
You also have to replace numero with number (typo).
And to go further, I suggest you to use a for loop instead the while loop, which I find more readable IMHO. The inner for loop can also stop when i <= number/2 to optimize a bit. Here is my suggestion of code:

#include <stdio.h>

int main(){

    int sum;

    for(int number = 1;number <= 1000; number++){
        sum = 0;

        for (int i = 1; i <= number/2; i++){
            if (number % i == 0){
                sum += i;
            }
        }

        if (sum == number){
            printf("%d is perfect\n", number);
        }
    }

    return 0;
}

Output:

6 is perfect
28 is perfect
496 is perfect