Skip to main content
added 254 characters in body
Source Link
user7530
  • 49.6k
  • 11
  • 88
  • 152

What do you mean by "fastest way"? Do you need the answer for many different $n$, or just one? Are you allowed to precompute anything? If so, how much time and space are you allowed to use?

Since $2^{32}$ is only about 4 billion, if you need to find primes for many different queries $n$, you can easily pregenerate the full sorted list of primes up to $2^{32}$ using the Sieve of Eratosthenes (or download the list from the Internet).

Then for each query $n$, do a binary search on the list of primes to find one in the desired interval.


Thinking more about this, you can do even better, with precomputation. For instance since $2^{32}+15$ is prime, you can return it for any $n\geq 2^{16}+8$. Then $2^{16}+15$ is prime and you can return it for any $ 2^8+8 \leq n <2^{16}+8$, etc.

What do you mean by "fastest way"? Do you need the answer for many different $n$, or just one? Are you allowed to precompute anything? If so, how much time and space are you allowed to use?

Since $2^{32}$ is only about 4 billion, if you need to find primes for many different queries $n$, you can easily pregenerate the full sorted list of primes up to $2^{32}$ using the Sieve of Eratosthenes (or download the list from the Internet).

Then for each query $n$, do a binary search on the list of primes to find one in the desired interval.

What do you mean by "fastest way"? Do you need the answer for many different $n$, or just one? Are you allowed to precompute anything? If so, how much time and space are you allowed to use?

Since $2^{32}$ is only about 4 billion, if you need to find primes for many different queries $n$, you can easily pregenerate the full sorted list of primes up to $2^{32}$ using the Sieve of Eratosthenes (or download the list from the Internet).

Then for each query $n$, do a binary search on the list of primes to find one in the desired interval.


Thinking more about this, you can do even better, with precomputation. For instance since $2^{32}+15$ is prime, you can return it for any $n\geq 2^{16}+8$. Then $2^{16}+15$ is prime and you can return it for any $ 2^8+8 \leq n <2^{16}+8$, etc.

Source Link
user7530
  • 49.6k
  • 11
  • 88
  • 152

What do you mean by "fastest way"? Do you need the answer for many different $n$, or just one? Are you allowed to precompute anything? If so, how much time and space are you allowed to use?

Since $2^{32}$ is only about 4 billion, if you need to find primes for many different queries $n$, you can easily pregenerate the full sorted list of primes up to $2^{32}$ using the Sieve of Eratosthenes (or download the list from the Internet).

Then for each query $n$, do a binary search on the list of primes to find one in the desired interval.