# perfect numbers

This is a discussion on perfect numbers within the C Programming forums, part of the General Programming Boards category; I want to find the first 5 perfect numbers. This is my code, but there is a problem. My logic ...

1. ## perfect numbers

I want to find the first 5 perfect numbers.

This is my code, but there is a problem. My logic is that I stay inside the loop until i have the fifth number (i.e. test == 4) but it simply hangs. If I change the condition from (test<4) to (test<3) I get the first 4 perfect numbers without a problem though... I start from number = 4 because 2 and 3 are prime.

Code:
```#include <stdio.h>

int main (int argc, const char * argv[])
{
long  perfect[5];
long  test = -1, i;
long  number = 4, sum;

while (test < 4)
{
sum = 0;

for (i=1; i< number; i++)
{
if (broj % i == 0) sum += i;
}

if (sum == number)
{
test++;
perfect[test] = number;
}

number ++;
}

printf("::::: THE PERFECT NUMBERS ARE : ");
for (i=0; i<5; i++)
{printf("\t%d", perfect[i]);}

return 0;
}```

2. Because you increment test before you use it.

Really, you should start with test = 0 and then increment at the end of the loop.

3. It's not hanging, it's doing something. The question is, how fast is it doing that something? For each number, you're looping about that many times (that is, you're looping 99 times for the number 100, 999 for 1000, 9999 for 10000, and so on). Those will take longer and longer to complete.

The fifth perfect number is 33550336. By the time you get there you will have performed trillions of loops. Your program will not complete in any reasonable amount of time.

On an unrelated note, %ld is used to print out longs, not %d.

4. I realized later that that takes toooo long. I need a different algorithm. thanks!