j
is an int
, presumably a 32-bit type, while i
is a long long int
, presumably a 64-bit type. Since i
is more than 2³², the value i/2
is more than the maximum value of the int
type, which is 2³¹-1. Therefore the comparison j<=i/2
is always true, and the loop for(j=2; j<=i/2; ++j)
never stops other than through the break
inside the body. But this break
is invoked only when j
is a divisor of i
, which never happens when i
is prime.
If you change j
to be a long long int
, I think your program works, but it will take a very long time to go through the inner loop — n1/2
iterations. A simple improvement is to stop at the square root of i
instead of half of i
. This alone makes the program run at a decent pace on my machine.
You should add fflush(stdout);
after each printf
call, otherwise the output is buffered until the program exits. Alternatively, first call setbuf(stdout, NULL)
to turn out output buffering.
This naive algorithm can definitely be improved: it repeats a lot of computations. You can store information in memory to avoid making the same tests over and over again; this is a time/memory trade-off. The sieve of Eratosthenes is a fairly simple algorithm that takes the trade-off to the other extreme: it maintains a table of sqrt(n2) bits, where the kth entry indicates whether k is prime. That would be workable here. You can also look at the open source BSD primes
utility to see how they do it.