Warm tip: This article is reproduced from serverfault.com, please click

The perfect number after 28

发布于 2020-11-28 01:42:56

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;
}
Questioner
wintersun
Viewed
0
MikeCAT 2020-11-28 09:45:54

You must initialize sum before each check.

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