Finding a prime number after a given number

前端 未结 6 1349
时光说笑
时光说笑 2020-12-23 16:24

How can I find the least prime number greater than a given number? For example, given 4, I need 5; given 7, I need 11.

I would like to know some ideas on best algor

6条回答
  •  一生所求
    2020-12-23 17:10

    Source: Wikipedia

    Bertrand's postulate (actually a theorem) states that if n > 3 is an integer, then there always exists at least one prime number p with n < p < 2n − 2. A weaker but more elegant formulation is: for every n > 1 there is always at least one prime p such that n < p < 2n.

    So if I am given a number, say n, than I can check in the range (n, 2*n) [open interval excluding n and 2*n]

    int GetNextPrime(int n)
    {
        bool isPrime = false;
        for (int i = n; i < 2 * n; ++i)
        {
        // go with your regular prime checking routine
        // as soon as you find a prime, break this for loop
        }
    }
    

提交回复
热议问题