What is the bottleneck in this primes related predicate?

后端 未结 4 1001
旧时难觅i
旧时难觅i 2021-01-19 21:05

So here it is : I\'m trying to calculate the sum of all primes below two millions (for this problem), but my program is very slow. I do know that the algorithm in itself is

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 22:04

    First, Prolog does not fail here.

    There are very smart ways how to generate prime numbers. But as a cheap start simply accumulate the primes in reversed order! (7.9s -> 2.6s) In this manner the smaller ones are tested sooner. Then, consider to test only against primes up to 141. Larger primes cannot be a factor.

    Then, instead of stepping only through numbers not divisible by 2, you might add 3, 5, 7.

    There are people writing papers on this "problem". See, for example this paper, although it's a bit of a sophistic discussion what the "genuine" algorithm actually was, 22 centuries ago when the latest release of the abacus was celebrated as Salamis tablets.

提交回复
热议问题