使用 Java 使用递归来减少 BigIntegers。该方法完全减少了数字,然后出于未知原因循环到“向上”的数字

问题描述 投票:0回答:1

我的作业是编写一个使用递归减少 BigInteger 的方法。如果数字是偶数,则将其分成两半,然后重复该过程,如果数字是奇数,则将其乘以 3,加 1,然后重复该过程,同时记录发生这种情况的次数。

递归继续,直到数字达到 1,然后我返回此过程发生的次数。

我认为我的方法应该很好用。他们不这样做。他们将 BigInteger 减少到 1,然后开始向上循环到一个随机数。我不明白为什么。任何帮助将不胜感激。

编辑:我所说的“向上循环”的意思是:在 big int 减少到 1 后,该方法继续“循环”,每次循环时,数字都会增加,计数器也会随着方法循环而减少。该方法中没有任何内容可以解释这一点,所以我不知道它为什么这样做。这个解释并没有真正的帮助,但我把 SystemPrintLn 放在各处并看到它做到了。

public int Problem9(BigInteger value) {
    BigInteger zero = BigInteger.valueOf(0);
    BigInteger one = BigInteger.valueOf(1);
    BigInteger two = BigInteger.valueOf(2);
    BigInteger three = BigInteger.valueOf(3);

    int count = reduceBigInt(value, zero, one, two, three, 1);
    
    return count;
}
public int reduceBigInt(BigInteger num, BigInteger zero,
        BigInteger one, BigInteger two, BigInteger three, int i) {
    
    if (num.equals(one))
        return i;
    else if ((num.remainder(two)) == zero)
        reduceBigInt((num.divide(two)), zero, one, two, three, i++);
    else
        reduceBigInt((num.multiply(three).add(one)), zero, one, two, three, i++);
    return i;
}
java recursion methods collatz
1个回答
0
投票

两项修改:

  1. i
  2. 上使用预自增
  3. 设置
    i
    返回
    reduceBigInt
    的值。
public class TestReduce {

    public static void main(String[] args) throws java.lang.Exception {
        BigInteger zero = BigInteger.valueOf(0);
        BigInteger one = BigInteger.valueOf(1);
        BigInteger two = BigInteger.valueOf(2);
        BigInteger three = BigInteger.valueOf(3);

        // 3 10 5 16 8 4 2 1

        int[] testData = { 4, 32, 11, 1 };

        for (int x : testData) {
            BigInteger value = BigInteger.valueOf(x);
            int count = reduceBigInt(value, zero, one, two, three, 1);
            System.out.println("v=" + value + " c=" + count);
        }

    }

    public static int reduceBigInt(BigInteger num, BigInteger zero, BigInteger one, BigInteger two, BigInteger three,
            int i) {

        if (num.equals(one))
            return i;
        else if ((num.remainder(two)) == zero)
            i = reduceBigInt((num.divide(two)), zero, one, two, three, ++i);
        else
            i = reduceBigInt((num.multiply(three).add(one)), zero, one, two, three, ++i);
        return i;

    }
}

和输出

v=4 c=3
v=32 c=6
v=11 c=15
v=1 c=1

包含样本测试输入/预期结果/实际结果以及有关错误结果的问题会很有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.