Efficient storage of prime numbers

前端 未结 9 1846
深忆病人
深忆病人 2020-12-07 16:46

For a library, I need to store the first primes numbers up to a limit L. This collection must have a O(1) lookup time (to check whether a number is prime or not) and it must

9条回答
  •  抹茶落季
    2020-12-07 17:34

    You can explicitly check more prime numbers to remove redundancy.

    At the moment you do this only for two, by checking for divisibility by two explicitly and then storing only for odd numbers whether they are prime.

    For 2 and 3 you get remainders 0 to 5, of which only 1 and 5 are not divisible by two or three and can lead to a prime number, so you are down to 1/3.

    For 2, 3, and 5 you get 8 numbers out of 30, which is nice to store in a byte.

    This is explained in more detail here.

提交回复
热议问题