Miller_Rabin · 大数
来源:互联网 发布:淘宝买家怎么导出订单 编辑:程序博客网 时间:2024/06/05 11:43
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();
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"); } }}
0 0
- Miller_Rabin · 大数
- 素数判定(Miller_Rabin) & 大数分解(Pollard_Pho)
- miller_rabin
- poj 2429 GCD & LCM Inverse(Miller_rabin 测试+pollard_rho大数分解)
- POJ 2429 GCD & LCM Inverse Pollard_Rho大数分解+Miller_Rabin
- [POJ 1811 Prime Test] Miller_Rabin + Pollard_rho 大数质数判断/质因子分解模板
- Miller_Rabin算法
- Miller_Rabin素数测试
- zjut 1517 Miller_Rabin
- POJ 1811 Miller_Rabin+Pollard_Rho
- Miller_Rabin素数测试
- Miller_Rabin素数测试
- Miller_Rabin素数测试
- Miller_Rabin 判断素数
- Miller_Rabin素数测试
- 【poj1811】Miller_Rabin and Pollard_rho
- 改进Miller_rabin素数测试
- Miller_Rabin算法 (poj 3641)
- tomcat配置文件server.xml详解
- structs2 请求json数据
- C++——数据结构之 顺序队列 链式队列?
- Android studio 安装篇
- hdu 1242 Rescue(优先队列)
- Miller_Rabin · 大数
- 双向一对多外联关系-XML配置属性
- 欢迎使用CSDN-markdown编辑器
- android开发中观察者模式的实际应用
- 彻底解决Spring MVC 中文乱码 问题
- Scala trait 未完待续
- sublime 修改字体
- 栈与队列(下)
- 大数据下的用户行为分析