Sieve of Eratosthenes using precalculated primes

后端 未结 1 1542
孤独总比滥情好
孤独总比滥情好 2021-01-07 03:01

I\'ve all prime numbers that can be stored in 32bit unsigned int and I want to use them to generate some 64bit prime numbers. using trial divis

相关标签:
1条回答
  • 2021-01-07 03:20

    Increment by 2, not 1. That's the minimal optimization you should always use - working with odds only. No need to bother with the evens.

    In C++, use vector<bool> for the sieve array. It gets automatically bit-packed.

    Pre-calculate your core primes with segmented sieve. Then continue to work by big enough segments that fit in your cache, without adding new primes to the core list. For each prime p maintain additional long long int value: its current multiple (starting from the prime's square, of course). The step value is twice p in value, or p offset in the odds-packed sieve array, where the i-th entry stands for the number o + 2i, o being the least odd not below the range start. No need to sort by the multiples' values, the upper bound of core primes' use rises monotonically.

    sqrt(0xFFFFFFFFFF) = 1048576. PrimePi(1048576)=82025 primes is all you need in your core primes list. That's peanuts.

    Integer arithmetics for long long ints should work just fine to find the modulo, and so the smallest multiple in range, when you first start (or resume your work).

    See also a related answer with pseudocode, and another with C code.

    0 讨论(0)
提交回复
热议问题