wintersun
wintersun

Reputation: 55

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;
}

Upvotes: 0

Views: 85

Answers (2)

yugsharma1711
yugsharma1711

Reputation: 71

You should have initialized the value of sum inside the while loop because it's value is not getting reset to 0 after a number check and it keeps on increasing the later value , so finally it would be resulting in a error .

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

You must initialize sum before each check.

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

Upvotes: 1

Related Questions