Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find largest prime number smaller than x [closed]

How do I calculate the largest prime number smaller than value x?

In actual fact, it doesn't have to be exact, just approximate and close to x.

x is a 32 bit integer.

The idea is that x is a configuration parameter. I'm using the largest prime number less than x (call it y) as the parameter to a class constructor. The value y must be a prime number.

like image 204
hookenz Avatar asked Jul 19 '11 03:07

hookenz


2 Answers

Some good info here on the function pi(x). Apparently,

pi(x) = the number of primes less than x

and you can approximate pi(x) with

x/(log x - 1)

while

the n-th prime of that list of primes is equal to approximately n(log n)
like image 70
marklar Avatar answered Oct 07 '22 06:10

marklar


How fast you need the program runs? And how frequently you calculate this problem?

If you need a fast achievement and don't care about the memory. You can generate an increasing prime table by sieve method then hold it during the program lifetime, and then when you what to find 'the largest prime number smaller than value x', just look up the table and in O(log N) time you can find an exact answer.

like image 32
Stan Avatar answered Oct 07 '22 06:10

Stan