Reputation: 35
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
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
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
Reputation: 42149
Three problems:
sum
must be initialized to zero for every i
, not just in the beginningj < i
, as per definition of perfect number the number itself is excludedsum == i
and following printf
must be moved outside the inner loop, otherwise it prints intermediate resultsUpvotes: 4