Detailed explanation of Miller_Rabin algorithm for prime number determination

Detailed explanation of Miller_Rabin algorithm for prime number determination 

E.g:

Goldbach

#include<bits/stdc++.h>
using namespace std;
unsigned long long n;
const int times = 5;
int number = 0;

unsigned long long Random( unsigned long long n ) //Generate a random number of [ 0 , n ]
{
    return ((double)rand( ) / RAND_MAX*n + 0.5);
}

unsigned long long q_mul( unsigned long long a, unsigned long long b, unsigned long long mod ) //快速计算 (a*b) % mod
{
    unsigned long long ans = 0;
    while(b)
    {
        if(b & 1)
        {
            b--;
            years = (years+ a)%mod;
        }
        b /= 2;
        a = (a + a) % mod;

    }
    return ans;
}

unsigned long long q_pow( unsigned long long a, unsigned long long b, unsigned long long mod ) //快速计算 (a^b) % mod
{
    unsigned long long ans = 1;
    while(b)
    {
        if(b & 1)
        {
            ans = q_mul( ans, a, mod );
        }
        b /= 2;
        a = q_mul( a, a, mod );
    }
    return ans;
}

bool witness( unsigned long long a, unsigned long long n )//The essence of the miller_rabin algorithm
{//Use the test operator a to test whether n is a prime number
    unsigned long long tem = n - 1;
    int j = 0;
    while(tem % 2 == 0)
    {
        has /= 2;
        j++;
    }
    // split n-1 into a^r * s

    unsigned long long x = q_pow( a, tem, n ); // get a^r mod n
    if(x == 1 || x == n - 1) return true; //If the remainder is 1, it is a prime number
    while(j--) //otherwise test condition 2 to see if there is a satisfied j
    {
        x = q_mul( x, x, n );
        if(x == n - 1) return true;
    }
    return false;
}

bool miller_rabin( unsigned long long n ) //Check if n is a prime number
{

    if(n == 2)
        return true;
    if(n < 2 || n % 2 == 0)
        return false; //If it is 2, it is a prime number, if <2 or an even number >2, it is not a prime number

    for(int i = 1; i <= times; i++) //Do times random tests
    {
        unsigned long long a = Random( n - 2 ) + 1; //Get the random check operator a
        if(!witness( a, n )) //Use a to check if n is a prime number
            return false;
    }
    return true;
}
int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		int a,b,c;
		char ch;
		cin>>n;
		if(n==2){
			cout<<1<<" "<<1<<endl;
		}
		else if(n==4){
			cout<<1<<" "<<3<<endl;
		}
		else{
			for(int i=3;i<=(n/2);i+=2){
				if(miller_rabin( i )&&miller_rabin( n-i )){
					cout<<i<<" "<<n-i<<endl;
					break;
				}
			}
		}
	}

	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324775332&siteId=291194637