Finding a prime number after a given number

前端 未结 6 1356
时光说笑
时光说笑 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:25

    I have done this before.

    Only addition is Bertrand's Theorem from Rajendra's Answer.

    And readymade code from topcoder.

    #include
    using namespace std;
    
    /* This function calculates (ab)%c */
    int modulo(int a,int b,int c){
        long long x=1,y=a; // long long is taken to avoid overflow of intermediate results
        while(b > 0){
            if(b%2 == 1){
                x=(x*y)%c;
            }
            y = (y*y)%c; // squaring the base
            b /= 2;
        }
        return x%c;
    }
    
    /* this function calculates (a*b)%c taking into account that a*b might overflow */
    long long mulmod(long long a,long long b,long long c){
        long long x = 0,y=a%c;
        while(b > 0){
            if(b%2 == 1){
                x = (x+y)%c;
            }
            y = (y*2)%c;
            b /= 2;
        }
        return x%c;
    }
    
    /* Miller-Rabin primality test, iteration signifies the accuracy of the test */
    bool Miller(long long p,int iteration){
        if(p<2){
            return false;
        }
        if(p!=2 && p%2==0){
            return false;
        }
        long long s=p-1;
        while(s%2==0){
            s/=2;
        }
        for(int i=0;i

提交回复
热议问题