Miller-Rabin素数测试

二次探测定理:如果是素数,且,则方程的解为

 

代码:

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
const int Times = 10;
typedef long long LL;

LL multi(LL a, LL b, LL m)
{
    LL ans = 0;
    a %= m;
    while(b)
    {
        if(b & 1)
        {
            ans = (ans + a) % m;
            b--;
        }
        b >>= 1;
        a = (a + a) % m;
    }
    return ans;
}

LL quick_mod(LL a, LL b, LL m)
{
    LL ans = 1;
    a %= m;
    while(b)
    {
        if(b & 1)
        {
            ans = multi(ans, a, m);
            b--;
        }
        b >>= 1;
        a = multi(a, a, m);
    }
    return ans;
}

bool Miller_Rabin(LL n)
{
    if(n == 2) return true;
    if(n < 2 || !(n & 1)) return false;
    LL m = n - 1;
    int k = 0;
    while((m & 1) == 0)
    {
        k++;
        m >>= 1;
    }
    for(int i=0; i


 

质数检测Java大数版:

 

题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1186

import java.io.*;
import java.util.*;
import java.math.BigInteger;
 
public class Main{
	    public static final int Times = 10;
	    
	    public static BigInteger quick_mod(BigInteger a,BigInteger b,BigInteger m){
	    		BigInteger ans = BigInteger.ONE;
	    		a = a.mod(m);
	    		while(!(b.equals(BigInteger.ZERO))){
	    				if((b.mod(BigInteger.valueOf(2))).equals(BigInteger.ONE)){
	    						ans = (ans.multiply(a)).mod(m);
	    						b = b.subtract(BigInteger.ONE);
	    				}
	    				b = b.divide(BigInteger.valueOf(2));
	    				a = (a.multiply(a)).mod(m);
	    		}
	    		return ans;
	    }
	    
	 	public static boolean Miller_Rabin(BigInteger n){
	 			if(n.equals(BigInteger.valueOf(2))) return true;
	 			if(n.equals(BigInteger.ONE)) return false;
	 			if((n.mod(BigInteger.valueOf(2))).equals(BigInteger.ZERO)) return false;
	 			BigInteger m = n.subtract(BigInteger.ONE);
	 			BigInteger y = BigInteger.ZERO;
	 			int k = 0;
	 			while((m.mod(BigInteger.valueOf(2))).equals(BigInteger.ZERO)){
	 					k++;
	 					m = m.divide(BigInteger.valueOf(2));
	 			}
	 			Random d = new Random();
	 			for(int i=0;i



你可能感兴趣的:(数论)