Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get the right output for perfect number algo

trying to write a perfect number algorithm but can’t get right output even thought 28 is a perfect number.

#include <stdio.h>

int main() {
    int x = 0;
    int sum;
    printf("enter a number: ");
    scanf("%d", &x);
    for(int i = 1;i < x;i++) {
        if(x % i==0) {
            printf("%d ", i);
            sum = sum + i;
        }
    }
    printf("\n");
    if(sum == x) {
        printf("it's a perfect number");
    }else {
        printf("it's not a perfect number");
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue might be coming from the way you declare the sum.

int sum;

When declaring it like this you only allocate space for an int in your memory but never set the value in the memory.

Wo when you do a sum = sum + 1, the sum is not defined and you try to add something to it. It will read in the memory a random value that is remaining here.

To prevent that, when you create an integer set it’s default value

ex : int sum = 0;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading