miller_rabin素数检测(java)

import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;

public class Main {
	//    没有用到的快速幂
	/*public static BigInteger multi(BigInteger a, BigInteger b,BigInteger p){
		BigInteger temp=BigInteger.valueOf(0);
		while (b.equals(BigInteger.valueOf(0))!=true){
			if (b.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))==true){
				temp=temp.add(a);
				temp=temp.mod(p);
			}
			a=a.multiply(BigInteger.valueOf(2));
			a=a.mod(p);
			b=b.divide(BigInteger.valueOf(2));
		}
		return temp;
	}
	public static BigInteger qpow(BigInteger a, BigInteger b,BigInteger p){
		BigInteger temp=BigInteger.valueOf(1);
		while (b.equals(BigInteger.valueOf(0))!=true){
			if (b.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))==true){
				temp=multi(temp,a,p);
			}	
			b=b.divide(BigInteger.valueOf(2));
			a=multi(a,a,p);
		}
		return temp;
	}*/
	public static boolean miller_rabin(BigInteger n){
		if (n.equals(BigInteger.valueOf(0))==true||n.equals(BigInteger.valueOf(1))==true) return false;
		if (n.equals(BigInteger.valueOf(2))==true) return true;
		int s=10;
		BigInteger k=n.subtract(BigInteger.valueOf(1));
		int t=0;
		//k.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))!=true    取模判1
		while (k.getLowestSetBit()!=0){
			t++;
			k=k.divide(BigInteger.valueOf(2));
		}
		Random ran = new Random();
		while (s-->0){
			BigInteger a=new BigInteger(100,ran).mod( n.subtract(BigInteger.valueOf(2))).add(BigInteger.valueOf(2) );
			BigInteger[] x= new BigInteger[105];
			x[0]=a.modPow(k,n);
			//x[0]=qpow(a,k,n);
			for (int i=1;i<=t;i++){
				x[i]=x[i-1].modPow(BigInteger.valueOf(2),n);
				//x[i]=multi(x[i-1],x[i-1],n);
				if (x[i].equals(BigInteger.valueOf(1))==true&&x[i-1].equals(BigInteger.valueOf(1))!=true&&x[i-1].equals(n.subtract(BigInteger.valueOf(1)))!=true) return false;
			}
			if (x[t].equals(BigInteger.valueOf(1))!=true) return false;
		}
		return true;
	}
	public static void main(String[] args) {
		Scanner cin= new Scanner(System.in);
		while (cin.hasNextBigInteger()){
			BigInteger n;
			n=cin.nextBigInteger();
			if (miller_rabin(n)==true) System.out.println("Yes");
			else System.out.println("No");
		}
		cin.close();	
	}
		
}


AC代码

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while(cin.hasNextBigInteger()){
			BigInteger n;
			n = cin.nextBigInteger();
			if (n.isProbablePrime(1)) System.out.println("Yes");
			else System.out.println("No");
		}
	}

}
这里有 miller_rabin素数检测 c的实现 https://blog.csdn.net/qq_41021816/article/details/80053766

你可能感兴趣的:(miller_rabin素数检测(java))