优化后的二次测试Miller_Rabin素性测试算法

ll random(ll n)

{

    return (ll)((double)rand()/RAND_MAX*n + 0.5);

}



ll pow_mod(ll a,ll p,ll n)

{

    if(p == 0)

        return 1;

    ll ans = pow_mod(a,p/2,n);

    ans = ans*ans%n;

    if(p%2)

        ans = ans*a%n;

    return ans;

}



bool Witness(ll a,ll n)

{

    ll m = n-1;

    int j = 0;

    while(!(m&1))

    {

        j++;

        m >>= 1;

    }

    ll x = pow_mod(a,m,n);

    if(x == 1 || x == n-1)

        return false;

    while(j--)

    {

        x = x*x%n;

        if(x == n-1)

            return false;

    }

    return true;

}



bool Miller_Rabin(ll n)

{

    if(n < 2)

        return false;

    if(n == 2)

        return true;

    if(!(n&1))

        return false;

    for(int i=1;i<=5;i++)   //5次测试

    {

        ll a = random(n-2)+1;

        if(Witness(a,n))

            return false;

    }

    return true;

}



int main()

{

    srand(time(NULL));

}

 

你可能感兴趣的:(算法)