开发者

Confused with sqrt() function in C

When i do like this, it works well in my code...

...

for (i = 2; i <= sqrt(500000); i++)

...

But do like

for (i = 2; i < sqrt(500000) + 1; i++)

executes after compile, error occurs saying Segmentation fault (core dumped).

for loop body is:

for (i = 2; i <= sqrt(500000); i++) {
        summation[i * i] += i;
        for (j = i + 1; j <= 500000 / i; j++) {
            summation[i * j]开发者_开发百科 += (i + j);
        }
    }

Is there any difference between the two for loops? Thanks


Your second loop run once more: 500000 is not a perfect square, so i < sqrt(500000) and i <= sqrt(500000) are always equal and the +1 ensure another iteration.


sqrt() will return a floating point number, so all comparisons are done for floating-point numbers and they are imprecise by design, so those two comparisons above can yield different results and thus in one of cases you'll have off-by-one and undefined behavior.


I've tried your code with gcc 4.3.4 under cygwin.

  • In the first case, i loops up to 707.
  • In the second case, i loops up to 708.

I bet that this last value triggers a buffer overflow somewhere in the body of the loop.


As others have already explained, the + 1 causes the loop to iterate once too often. Then summation[i * i] or summation[i * j] accesses beyond the allocated size of summation. The solution is to either increase the allocated size accordingly or make sure that the condition is correct (not doing + 1) and you thus do not run over the end of the array.

But also, like others already said, you should not use a floating point value (result of sqrt) with an integer comparison as floating point values are... tricky. I'm not sure whether in this case the int gets casted to float or vice versa, but whichever way it's not the right thing to do.


did you try this?

for (i = 2; i < (sqrt(500000) + 1); i++)

Is your i a floating pont variable?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜