import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;
public class FermatTest
{
public static void main(String[] args)
{
Scanner ch = new Scanner(System.in);
System.out.println("n:");
BigInteger n = ch.nextBigInteger();
System.out.println("K:");
int K = ch.nextInt();
int k=0,i;
BigInteger b= BigInteger.valueOf(0);
Random R =new Random();
while(k<K)
{
Boolean flag = false;
while(! flag)
{
i = R.nextInt(n.subtract(BigInteger.valueOf(4)).intValue());
//i的范围是0~n-4
b =BigInteger.valueOf(i+2);
//b的范围是2~n-2
flag = true;
}
BigInteger f = n.gcd(b);
BigInteger r = b.modPow(n.subtract(BigInteger.valueOf(1)),n);
if(f.intValue()>1)
break;
else if(r.intValue()!=1)
break;
else System.out.println(n+"可能是素数");
k++;
}
if(k==K)
{
double o = 1.0-1.0/Math.pow(2,k);
System.out.println("n可能是素数的概率是"+o);
}
}
}
本来想用大数值去实现费马素性检验,但是随机数生成那,却不能使用大数值.....