关于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; ...
随机推荐
- MyBatis(6)——分页的实现
分页的实现 a)通过mysql的分页查询语句: 说明:sql的分页语句格式为select * from aaa limit #{startIndex},#{pageSize} //---------- ...
- date命令的帮助信息,使用date命令输出数字做为命名标题则不会有重复标题
date命令的帮助信息,如下图 原文来自 https://blog.csdn.net/yz18931904/article/details/80985345 [root@localhost sourc ...
- nginx的负载均衡配置
1.下载nginx的压缩包,可以去官网下载 2.解压缩,可以看到其中有个conf的文件夹,在该目录中,nginx.conf配置文件就是核心配置文件 3.默认配置 #user nobody; worke ...
- markdown pic
Markdown 图片 Markdown 图片语法格式如下:   开头一个感叹号 ! 接着一个方括 ...
- web项目获取路径
Java获取路径的各种方法: (1).request.getRealPath("/"); //不推荐使用获取工程的根路径 (2).request.getRealPath(requ ...
- confluence-工具安装
wiki 企业级的应用知识库,个人感觉还是很不错的,所以自己本地也搭一个玩玩: 1.下载confluence wget https://downloads.atlassian.com/software ...
- JavaScript - 获取当前页面某个节点的个数
document.getElementsByTagName(<tag_name>).length;
- opencv:图像的读取,显示,写入文件
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace st ...
- 创业学习---《如何展开竞争情报调研》--D-1.调研模块---HHR计划---以太一堂
第一:<开始学习> 1,投资人看人标准:人品好:创业热情:学习能力. 2,思考题:请你预判一个最靠谱的方向来创业,你会怎么调研呢? 3,预热思考题: (1)在这个赛道,究竟有哪些重要竞争对 ...
- python日常题目小练习
1.使用while循环输出1 2 3 4 5 6 8 9 10 i=0 while i<10: i+=1 if i==7: continue print(i) 结果: 2.求1-100的所有数的 ...