Optimization of Algorithm [closed]

╄→гoц情女王★ 提交于 2019-12-04 16:48:18

You have an int overflow here:

for (j = i, f = 0; j <= N; j *= i)

If 46340 < i < 65536 and for many larger i, in the second iteration j will be negative if overflow wraps around (it is undefined behaviour, so anything could happen).

Replace it with e.g.

for(j = N / i, f = 0; j > 0; j /= i) {
    f += j;
}

It is, however, unlikely that the extra iterations due to the overflow would cause a "time limit exceeded", that will likely only cause wrong results.

So the generic advice is

  • Sieve only odd numbers, perhaps also eliminate multiples of 3 from the sieve. Eliminating the odd numbers from the sieve roughly halves the time needed to sieve.
  • Don't use an entire int for the flags, use bits or at least chars. That gives better cache locality and a further speedup.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!