import java.math.BigInteger;
import java.util.Random;
public class Primetest {
private static int size=15;
private static Random r=new Random();
private static BigInteger two=new BigInteger("2");
private static BigInteger three=new BigInteger("3");
public static void main(String[] args) {
while(true)
{
BigInteger p=new BigInteger(size,r);
if(isprime(p)==true)
{
System.out.println("prime="+p);
break;
}
}
}
public static boolean isprime(BigInteger n)
{
if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0)
{
return true;
}
BigInteger half=n.divide(two);
for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
return false;
}
}
return true;
}
}此代码选择一个随机素数BigInteger数。我想要一个2048位的BigInteger素数,但它只适用于15位。有人能帮我吗?
发布于 2014-03-05 08:47:44
这是代码审查,所以我不会试图找到它不支持2048位BigIntegers的地方,但是我将告诉您在您的代码中看到了什么:
你应该根据你的语言的命名约定来选择你的名字:Primetest应该是PrimeTest,two应该是TWO (也见下面关于适当的变量范围),isprime应该是isPrime,等等。
对于用于多行代码的任何代码- r、n等,也不要使用单个字母名称。
变量名应该清楚地说明它们的用途half意味着数字1/2,特别是在one和two旁边。实际上它意味着输入数字的一半。它被用作最大可能的除数,所以称之为- maxDivisor。
size也是如此--它应该是MAX_BITS_RANGE (顺便说一句,当您将它的值更改为2048年时会发生什么?)
当事情没有改变的时候
如果您拥有的数据不随时间而变化(如数字two) -- static是好的,使其成为常量(static final)更好:
private static final int MAX_BITS_RANGE=15;
private static final Random GENERATOR=new Random();
private static final BigInteger TWO=new BigInteger("2");
private static final BigInteger THREE=new BigInteger("3");if (isPrime(x) == true)与if (isPrime(x))完全相同。
在您的代码中的不同位置,您检查等式是否为n.compareTo(BigInteger.ONE)==0或n.mod(i).equals(BigInteger.ZERO) --选择一种方式--并坚持它。
*加入@Marc-Andre的意见:
您还应该与您的缩进和大括号位置保持一致。虽然甲骨文的建议是把开式支撑放在行尾,
while(true) {
}不是在下一个开始(我也喜欢),其他样式也被使用(一些比其他更广泛):
// Allman Style
while (true)
{
}
// Whitesmiths Style
while (true)
{
}但你应该选择一种风格,并坚持它,以防止阅读错误,和一般的头部疼痛的代码阅读器.
发布于 2014-07-21 18:15:51
我可以向您建议一些可以大幅度减小isPrime代码大小的方法。
public static boolean isPrime(BigInteger n) {
BigInteger lessOne = n.subtract(BigInteger.ONE);
// get the next prime from one less than number and check with the number
return lessOne.nextProbablePrime().compareTo(n) == 0;
}https://codereview.stackexchange.com/questions/43490
复制相似问题