Waffl
Waffl

Reputation: 35

Perfect numbers in C, won't print

I have the following program, the perfect numbers won't print, only output are the numbers 1 and 2, which are not perfect. What's wrong, is it a scope problem or is it the loops? Adding break statement after print statement causes output of all numbers 1 - 99.

int sum = 0;

for (int i = 1; i < 100; i++) {

    for (int j = 1; j <= i; j++) {

        if (i % j == 0){

            sum += j;}

        if (sum == i){

            printf("%d\n", i);

        }
    }
}

Upvotes: 1

Views: 162

Answers (3)

user3629249
user3629249

Reputation: 16540

given this code, which incorporates all the prior comments/answers:

#include <stdio.h>


int main( void )
{
    int sum = 0;

    for (int i = 1; i < 100; i++)
    {
        sum = 0; // reset on each new number

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

        if (sum == i)
        {
             printf("%d\n", i);
        } // end if
    } // end for
    return 0;
} // end function: main

the output is 6 and 28

Upvotes: 1

mlwn
mlwn

Reputation: 1187

I think you don't need to test all the way to i (j < i)... it is enough to reach i / 2 ...

#include<stdio.h>
void main() {
    int sum;
    for (int i = 1; i < 100; i++) {
        sum = 0;
        for (int j = 1; j <= i/2; j++) {
            if (i % j == 0) {
                sum += j;
            }
        }
        if (sum == i) {
            printf("%d\n", i);
        }
    }
}

Upvotes: 0

Arkku
Arkku

Reputation: 42149

Three problems:

  1. sum must be initialized to zero for every i, not just in the beginning
  2. the second loop condition must be j < i, as per definition of perfect number the number itself is excluded
  3. the check for sum == i and following printf must be moved outside the inner loop, otherwise it prints intermediate results

Upvotes: 4

Related Questions