First of all, sqrt(x)
should be faster and more accurate than pow(x,0.5)
, why do you think it’s in the library? Second, you’re probably getting a wrong answer because your loop termination condition is testing a floating-point number. A tiny round-off somewhere in one of those 2 million loops is probably enough to throw off the total. Finally, you’re calculating a floating point sqrt() twice inside each iteration of the loop, which is terribly slow.
Instead of
for (j = 0; j <= sqrt(i); ++j) . . .
try
limit = (int)(sqrt(i) + 0.5);
for (j = 0; j <= limit; ++j) . . .
1
solved Different results on using sqrt() and pow() functions