Efficient storage of prime numbers

前端 未结 9 1883
深忆病人
深忆病人 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:33

    How about an Interval Tree? http://www.geeksforgeeks.org/interval-tree/

    It may not be O(1) but it's really fast. Like maybe O(log(p(n))) where p(n) is the number of primes till the number n. This way you'll the memory you'll need will be in proportion to the number of primes only, greatly cutting the memory cost.

    For example suppose you find a prime at say p1 and then the next one at p2, Insert interval (p1,p2) and so on and when you run a search for any number in that range it will return this interval and you can return p2 which would be the answer in your case.

提交回复
热议问题