Miller_Rabin · 大数

51nod 1186 质数检测 V2
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1186

给出一个很大的数字N,2<=N<=10^30。判断他是不是素数。

分析:数字很大,使用java的BigInteger解决。
在这个过程中犯了许多低级错误。哎,我的java基础啊。

相关知识点记录:

==比较的是对象的地址,也就是是否是同一个对象;

equal比较的是对象的值。

Math.random() 产生[0-1)的随机浮点数
util.Random:
Random():创建一个新的随机数生成器
Random r=new Random();
int n = r.nextInt();  //生成-231到231-1之间的整数
生成[0,x)区间的整数:
int n2 = r.nextInt(x);
or
n2 = Math.abs(r.nextInt() % x);

嗯,其他就是写代码了。

import java.util.*;
import java.math.BigInteger;
public class Main {
    static BigInteger two=BigInteger.valueOf(2),
            one=BigInteger.ONE,
            zero=BigInteger.ZERO;
    static BigInteger quick_mod(BigInteger a,BigInteger m,BigInteger p){
        BigInteger ans=one;
        a=a.mod(p);
        while(m.compareTo(zero)>0){
            if(m.mod(two).equals(one))ans=ans.multiply(a).mod(p);
            a=a.multiply(a).mod(p);
            m=m.divide(two);
        }
        return ans;
    }
    static boolean Miller_Rabin(BigInteger p){
        if(p.equals(two)) return true;
        if(p.equals(one)||p.mod(two).equals(zero)) return false;
        BigInteger m=p.subtract(one);
        int sum=0;
        while(m.mod(two).equals(zero)){
            sum++;
            m=m.divide(two);
        }
        for(int i=0;i<10;i++){
            int r=(int)(Math.random()*10000);
            BigInteger a=BigInteger.valueOf(r);
            if(a.compareTo(p)>0)a=a.mod(p);
            while(a.equals(zero)){
                r=(int)(Math.random()*10000);
                a=BigInteger.valueOf(r);
                if(a.compareTo(p)>0)a=a.mod(p);
            }
            BigInteger x=quick_mod(a,m,p),g=zero;
            for(int j=0;j<sum;j++){
                g=x.multiply(x).mod(p);
                if(g.equals(one)&&x.equals(one)==false&&x.equals(p.subtract(one))==false)
                    return false;
                x=g;
            }
            if(g.equals(one)==false) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        BigInteger p=zero;
        while(cin.hasNext()){
            p=cin.nextBigInteger();
            if(Miller_Rabin(p)) System.out.println("Yes");
            else System.out.println("No");
        }

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值