首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BigInteger素数测试

BigInteger素数测试
EN

Code Review用户
提问于 2014-03-05 08:25:18
回答 2查看 11.3K关注 0票数 5
代码语言:javascript
复制
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位。有人能帮我吗?

EN

回答 2

Code Review用户

发布于 2014-03-05 08:47:44

这是代码审查,所以我不会试图找到它不支持2048位BigIntegers的地方,但是我将告诉您在您的代码中看到了什么:

命名约定

你应该根据你的语言的命名约定来选择你的名字:Primetest应该是PrimeTesttwo应该是TWO (也见下面关于适当的变量范围),isprime应该是isPrime,等等。

对于用于多行代码的任何代码- rn等,也不要使用单个字母名称。

专有名称

变量名应该清楚地说明它们的用途half意味着数字1/2,特别是在onetwo旁边。实际上它意味着输入数字的一半。它被用作最大可能的除数,所以称之为- maxDivisor

size也是如此--它应该是MAX_BITS_RANGE (顺便说一句,当您将它的值更改为2048年时会发生什么?)

当事情没有改变的时候

如果您拥有的数据不随时间而变化(如数字two) -- static是好的,使其成为常量(static final)更好:

代码语言:javascript
复制
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)==0n.mod(i).equals(BigInteger.ZERO) --选择一种方式--并坚持它。

*加入@Marc-Andre的意见:

您还应该与您的缩进和大括号位置保持一致。虽然甲骨文的建议是把开式支撑放在行尾,

代码语言:javascript
复制
while(true) {
}

不是在下一个开始(我也喜欢),其他样式也被使用(一些其他更广泛):

代码语言:javascript
复制
// Allman Style
while (true)
{
}

// Whitesmiths Style
while (true)
    {
    }

但你应该选择一种风格,并坚持它,以防止阅读错误,和一般的头部疼痛的代码阅读器.

票数 5
EN

Code Review用户

发布于 2014-07-21 18:15:51

我可以向您建议一些可以大幅度减小isPrime代码大小的方法。

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/43490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档