首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何不断提升BigInteger的价值?

如何不断提升BigInteger的价值?
EN

Stack Overflow用户
提问于 2016-01-13 00:15:55
回答 2查看 5.7K关注 0票数 2

我有一系列的BigInteger问题,需要使用不断增加的BigInteger。我提出了一个循环,但这非常棘手,因为BigIntegers和BigDecimals是不可变的。

这是我正在尝试制作的一个程序的示例。这是一种试图找到大于Long.MAX_VALUE且可被2或3整除的BigIntegers的方法。

代码语言:javascript
复制
    public void divisibleBy2Or3() {
    BigInteger min = new BigInteger("9223372036854775808");
    int j = 0;
    BigInteger increment = new BigInteger("1");
    BigInteger divideBy2 = new BigInteger("2");
    BigInteger divideBy3 = new BigInteger("3");
    while (j < 10) {
        BigInteger a = min.add(increment);
        BigInteger b = a.divide(divideBy2); BigInteger c = a.divide(divideBy3);
        if (b.multiply(divideBy2) == a || c.multiply(divideBy3) == a) {
            System.out.print(a + " ");
            j++;
        }
    }
}

这段代码的问题在于,我似乎无法弄清楚如何让我为循环的每次迭代测试的BigInteger在每次迭代时自动添加。我还有点不确定multiply方法是否真的适用于这个场景,因为每当我运行程序时,它都会挂起并显示一个空白控制台

EN

回答 2

Stack Overflow用户

发布于 2016-01-13 00:24:07

您需要使用在循环外部声明的变量来跟踪当前值-否则它会一直返回到min + 1

代码语言:javascript
复制
static final BigInteger ONE = BigInteger.ONE;
static final BigInteger TWO = ONE.add(ONE);
static final BigInteger THREE = TWO.add(ONE);

public void divisibleBy2Or3() {
    BigInteger min = new BigInteger("9223372036854775808");
    int j = 0;
    // Add this.
    BigInteger value = min;
    while (j < 10) {
        value = value.add(ONE);
        BigInteger b = value.divide(TWO);
        BigInteger c = value.divide(THREE);
        if (b.multiply(TWO).equals(value) || c.multiply(THREE).equals(value)) {
            System.out.print(value + " ");
            j++;
        }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2016-01-13 01:07:03

为什么你甚至需要搜索这些数字?

简单的纸笔计算显示了一个简单的属性,即可被2或3整除的数字以及它们的顺序,即可被2和3整除的任意起始数字x

代码语言:javascript
复制
x  x + 2  x + 3  x + 4  [x + 6
                        //the repetition starts here

使用这一点,我们可以很容易地生成与约束匹配的数字:

代码语言:javascript
复制
//x mod 3 = 2
BigInteger x = new BigInteger("9223372036854775808");
BigInteger[] next_add = new BigInteger[]{
    BigInteger.ONE,
    BigInteger.ONE,
    new BigInteger("2"),
    new BigInteger("2")
};

//generate and print matching integer
for(int i = 0 ; i < searchedNumber ; i++){
    x = x.add(next_add[i % 4]);
    System.out.println(x);
}

一般提示:使用x % divBy == 0而不是(x / divBy) * divBy == x检查可分性,以提高效率和可读性。

这种代码的优点是,与您的代码相比,只有2/3的循环周期用于相同数量的搜索值,并且不需要成本高昂的可分性检查。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34748596

复制
相关文章

相似问题

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