且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

高效的算法,得到两个大数的质数

更新时间:2023-02-26 18:43:44

我记得解决这个问题是这样的:

I remember solving the problem like this:

  1. 使用埃拉托色尼的以生成以下的sqrt(10亿)的所有素数=〜32 000 在一个数组素数
  2. 对于每个编号之间的 M X N 如果它是主要通过测试整除反对数只考< =的sqrt(x)从数组素数。因此,对于 X = 29 你会如果它是divisibile通过只考2,3,5
  1. Use the sieve of eratosthenes to generate all primes below sqrt(1000000000) = ~32 000 in an array primes.
  2. For each number x between m and n only test if it's prime by testing for divisibility against numbers <= sqrt(x) from the array primes. So for x = 29 you will only test if it's divisibile by 2, 3 and 5.

有一个在检查可分对非质数没有任何意义,因为如果 X整除非黄金是,则存在一个素点&LT;是,使得由P X [整除,因为我们可以写作为产品素数。例如, 12 6 整除,但 6 = 2 * 3 ,这意味着 12 也整除 2 3 。通过生成所有需要的素数提前(有在这种情况下,非常少),则显著减少所需的实际素性测试的时间。

There's no point in checking for divisibility against non-primes, since if x divisible by non-prime y, then there exists a prime p < y such that x divisible by p, since we can write y as a product of primes. For example, 12 is divisible by 6, but 6 = 2 * 3, which means that 12 is also divisible by 2 or 3. By generating all the needed primes in advance (there are very few in this case), you significantly reduce the time needed for the actual primality testing.

这会得到接受,并且不需要任何的优化或修改筛,这是一个pretty的清洁实施。

This will get accepted and doesn't require any optimization or modification to the sieve, and it's a pretty clean implementation.

您可以更快地做到这一点通过要概括筛产生在区间的质数 [左,右] ,不是 [2,右] 喜欢它通常$ psented的教程,教材p $。这可以得到pretty的丑但是,这是没有必要的。但是,如果有人有兴趣,请参见:

You can do it faster by generalising the sieve to generate primes in an interval [left, right], not [2, right] like it's usually presented in tutorials and textbooks. This can get pretty ugly however, and it's not needed. But if anyone is interested, see:

http://pastie.org/9199654 和this联答案。