Search code examples
cloopsperfect-numbers

The perfect number after 28


I've written a simple program to find the perfect number that is immediately after 28 (which is 496), however it is not working. Not sure what I'm doing wrong.

#include <stdio.h>

int main(){

    int num=29, sum=0, aux=1;

    while(aux!=0){
        for(int i=1; i<num; i++){
            if(!(num%i)){
                sum+=i;
            }
        }

        if(sum == num){
            printf("%d", sum);
            aux=0;
        }else{
            num++;
        }
    }

    return 0;
}

Solution

  • You must initialize sum before each check.

        while(aux!=0){
            sum = 0; /* add this */
            for(int i=1; i<num; i++){