关于Java大整数是否是素数
题目描述
请编写程序,从键盘输入两个整数m,n,找出等于或大于m的前n个素数。
输入格式:
第一个整数为m,第二个整数为n;中间使用空格隔开。例如: 103 3
输出格式:
从小到大输出找到的等于或大于m的n个素数,每个一行。例如: 103 107 109
输入样例:
9223372036854775839 2
输出样例:
9223372036854775907
9223372036854775931
用到的Api:
本题代码:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
String sc = in.next();
BigInteger m = new BigInteger(sc);
int n = in.nextInt();
int i=0;
while(i<n){
if(isPrime(m)){
System.out.println(m);
i++;
}
m=m.add(BigInteger.ONE);
}
}
public static boolean isPrime(BigInteger num) {
return num.isProbablePrime(50);
}
}
api的相关实现代码:
/**
* Returns {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite. If
* {@code certainty} is ≤ 0, {@code true} is
* returned.
*
* @param certainty a measure of the uncertainty that the caller is
* willing to tolerate: if the call returns {@code true}
* the probability that this BigInteger is prime exceeds
* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of
* this method is proportional to the value of this parameter.
* @return {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite.
*/
public boolean isProbablePrime(int certainty) {
if (certainty <= 0)
return true;
BigInteger w = this.abs();
if (w.equals(TWO))
return true;
if (!w.testBit(0) || w.equals(ONE))
return false;
return w.primeToCertainty(certainty, null);
}
// Single Bit Operations
/**
* Returns {@code true} if and only if the designated bit is set.
* (Computes {@code ((this & (1<<n)) != 0)}.)
*
* @param n index of bit to test.
* @return {@code true} if and only if the designated bit is set.
* @throws ArithmeticException {@code n} is negative.
*/
public boolean testBit(int n) {
if (n < 0)
throw new ArithmeticException("Negative bit address");
return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
}
/**
* Returns {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite.
*
* This method assumes bitLength > 2.
*
* @param certainty a measure of the uncertainty that the caller is
* willing to tolerate: if the call returns {@code true}
* the probability that this BigInteger is prime exceeds
* {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of
* this method is proportional to the value of this parameter.
* @return {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite.
*/
boolean primeToCertainty(int certainty, Random random) {
int rounds = 0;
int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
// The relationship between the certainty and the number of rounds
// we perform is given in the draft standard ANSI X9.80, "PRIME
// NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
int sizeInBits = this.bitLength();
if (sizeInBits < 100) {
rounds = 50;
rounds = n < rounds ? n : rounds;
return passesMillerRabin(rounds, random);
}
if (sizeInBits < 256) {
rounds = 27;
} else if (sizeInBits < 512) {
rounds = 15;
} else if (sizeInBits < 768) {
rounds = 8;
} else if (sizeInBits < 1024) {
rounds = 4;
} else {
rounds = 2;
}
rounds = n < rounds ? n : rounds;
return passesMillerRabin(rounds, random) && passesLucasLehmer();
}
/**
* Returns true iff this BigInteger passes the specified number of
* Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
* 186-2).
*
* The following assumptions are made:
* This BigInteger is a positive, odd number greater than 2.
* iterations<=50.
*/
private boolean passesMillerRabin(int iterations, Random rnd) {
// Find a and m such that m is odd and this == 1 + 2**a * m
BigInteger thisMinusOne = this.subtract(ONE);
BigInteger m = thisMinusOne;
int a = m.getLowestSetBit();
m = m.shiftRight(a);
// Do the tests
if (rnd == null) {
rnd = ThreadLocalRandom.current();
}
for (int i=0; i < iterations; i++) {
// Generate a uniform random on (1, this)
BigInteger b;
do {
b = new BigInteger(this.bitLength(), rnd);
} while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
int j = 0;
BigInteger z = b.modPow(m, this);
while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
if (j > 0 && z.equals(ONE) || ++j == a)
return false;
z = z.modPow(TWO, this);
}
}
return true;
}
/**
* Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
*
* The following assumptions are made:
* This BigInteger is a positive, odd number.
*/
private boolean passesLucasLehmer() {
BigInteger thisPlusOne = this.add(ONE);
// Step 1
int d = 5;
while (jacobiSymbol(d, this) != -1) {
// 5, -7, 9, -11, ...
d = (d < 0) ? Math.abs(d)+2 : -(d+2);
}
// Step 2
BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
// Step 3
return u.mod(this).equals(ZERO);
}
关于Java大整数是否是素数的更多相关文章
- 自己动手写Java大整数《3》除法和十进制转换
之前已经完毕了大整数的表示.绝对值的比較大小.取负值.加减法运算以及乘法运算. 详细见前两篇博客(自己动手写Java * ). 这里加入除法运算. 另外看到作者Pauls Gedanken在blog( ...
- HDU2303(数论)大整数求余+素数筛选
Sample Input 143 10 143 20 667 20 667 30 2573 30 2573 40 0 0 Sample Output GOOD BAD 11 GOOD BAD 23 ...
- JAVA大整数傻瓜入门
http://blog.csdn.net/skiffloveblue/article/details/7032290..先记着
- Coefficient Computation (大整数、Java解决)
Coefficient Computation UVALive8265 题意:计算组合数C(n,k)的值并将值按给定的进制输出. 思路:Java大整数类硬上. PS:刚刚学完Java的大整数类,结果却 ...
- hdu 1316(大整数)
How Many Fibs? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...
- 【Java编程】Java中的大整数计算
在上一篇文章中,我们实现了c语言中的大整数的运算,并且用Miller-Rabin算法实现了对大素数的测试.本来我准备用Java代码实现大整数的运算,查了一下资料发现Java中java.math的Big ...
- 【老鸟学算法】大整数乘法——算法思想及java实现
算法课有这么一节,专门介绍分治法的,上机实验课就是要代码实现大整数乘法.想当年比较混,没做出来,颇感遗憾,今天就把这债还了吧! 大整数乘法,就是乘法的两个乘数比较大,最后结果超过了整型甚至长整型的最大 ...
- [大整数乘法] java代码实现
上一篇写的“[大整数乘法]分治算法的时间复杂度研究”,这一篇是基于上一篇思想的代码实现,以下是该文章的连接: http://www.cnblogs.com/McQueen1987/p/3348426. ...
- Java 实现大整数加减乘除
自己用Java实现的大整数加减乘除运算.还有可以改进的地方,有兴趣的童鞋可以加以改进.仅供参考,请勿转载! package barrytest; import java.util.ArrayList; ...
随机推荐
- fiddler中文乱码解决方案
只用添加一个注册表变量就行 cmd窗口执行regedit命令,在弹出的注册表编辑界面找到fiddler 右击新建一个字符传值 HeaderEncodingGBK 结果如上图右所示~ 重启fiddler ...
- SqlDataAdapter对象
https://blog.csdn.net/qq_39657909/article/details/80615465 一.特点介绍 1.表示用于填充 DataSet 和更新 SQL Server 数据 ...
- linux下安装keepalived
keepalived安装文档 1. 安装环境 su - root yum -y install kernel-devel* yum -y install openssl-* yum -y instal ...
- 安卓按键:读取txt开头出现未知字符的问题
很多时候 我们读取txt 用traceprint输出后 最头上会莫名其妙多出一个问号 但是你用问号匹配他 却匹配不到 就是1个未知字符 这个到底是什么 怎么避免出现这个东西呢 这个主要是txt文件 ...
- redis 基础操作教程
1.linux 安装redis : Linux 下安装 下载地址:http://redis.io/download,下载最新稳定版本. 本教程使用的最新文档版本为 2.8.17,下载并安装: $ wg ...
- Cesium 基于MapBox底图加载3DTiles 模型
3DTiles 模型采用 CATIA V5 R22 --->3dxml --->GLB--->B3DM var extent = Cesium.Rectangle.fromDeg ...
- dfs序与求子树子节点(染了色)的个数
https://blog.csdn.net/hpu2022/article/details/81910490 https://blog.csdn.net/qq_39670434/article/det ...
- Spring IoC(一)bean实例化和依赖注入
1.IoC容器概述 IoC 全称为 Inversion of Control,翻译为 “控制反转”,它还有一个别名为 DI(Dependency Injection),即依赖注入. 所谓 IOC ,就 ...
- IIS-URL重写模块配置参考
本文提供了URL重写模块的概述,并解释了该模块使用的配置概念. 功能概述URL重写模块将请求URL重写为显示给用户或Web应用程序的简单,用户友好和搜索引擎友好的地址.URL重写使用定义的规则进行评估 ...
- dp(完全背包)
有 NN 种物品和一个容量是 VV 的背包,每种物品都有无限件可用. 第 ii 种物品的体积是 vivi,价值是 wiwi. 求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大. ...