【问题标题】:How to keep increasing the value of a BigInteger?如何不断增加 BigInteger 的价值?
【发布时间】:2016-01-12 16:15:54
【问题描述】:

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

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

    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,以便在每次迭代中添加自身。我也有点不确定乘法方​​法是否真的适用于这种情况,因为每当我运行程序时,它都会挂起并显示一个空白控制台

【问题讨论】:

  • 只需重新分配给相同的变量以更改它。你没有得到任何输出的原因是你的比较是错误的。使用.equals 而不是==
  • 为什么需要搜索这些值? 2 和 3 的倍数具有明确定义的属性,无需搜索即可生成此类值。
  • BigInteger b =new BigInteger("123"); b = b.add( BigInteger.ONE );

标签: java biginteger


【解决方案1】:

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

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++;
        }
    }
}

【讨论】:

    【解决方案2】:

    为什么您甚至需要搜索这些数字?
    只需一点纸笔计算就可以显示出可被 2 或 3 整除的数字的简单属性,以及可被 2 和 3 整除的任意起始数字x 的顺序:

    x  x + 2  x + 3  x + 4  [x + 6
                            //the repetition starts here
    

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

    //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 的循环循环用于相同数量的搜索值,并且不需要昂贵的可分性检查。

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 2011-03-30
      • 2021-10-11
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多