使递归函数迭代

时间:2018-10-30 16:32:24

标签: java math recursion iteration

赋值:根据以下公式计算a n

  • a 0 = 1
  • a 1 = 3
  • a 2 = 5
  • a n = a n-1 * a 2 n-2 * a 3 n-3

我在使函数迭代时遇到麻烦。我想出了如何递归地做它。在一般情况下,我将如何专门针对此任务进行操作?

我的递归代码:

public static BigInteger recurs(int bigInteger){
    BigInteger sum;

    if (bigInteger == 0) {
        sum = new BigInteger(String.valueOf("1"));
    } else if (bigInteger == 1) {
        sum = new BigInteger(String.valueOf("3"));
    } else if (bigInteger == 2) {
        sum = new BigInteger(String.valueOf("5"));
    } else {
        sum = recurs(bigInteger-1).multiply(recurs(bigInteger-2).pow(2).multiply(recurs(bigInteger-3).pow(3)));
    }

    return sum;

}

3 个答案:

答案 0 :(得分:2)

您需要记住最后三个值,并根据最后一个值每次计算一个新值。

public static BigInteger iter(int n) {
    BigInteger a = BigInteger.valueOf(1);
    BigInteger b = BigInteger.valueOf(3);
    BigInteger c = BigInteger.valueOf(5);
    switch (n) {
        case 0: return a;
        case 1: return b;
        case 2: return c;
        default:
            for (int i = 2; i < n; i++) {
                BigInteger next = c.multiply(b.pow(2)).multiply(a.pow(3));
                a = b;
                b = c;
                c = next;
            }
            return c;
    }
}

请注意,这是O(n)而不是O(n ^ 3)

答案 1 :(得分:-1)

给您一个提示:

初始化一个大小为n的数组,该数组将保存答案。例如,第ith个索引将存储a_i的答案。初始化a_0,a_1和a_2为您提供的值(在您的情况下为1,3和5)。现在从索引3开始迭代,并使用您的公式计算a_i。

答案 2 :(得分:-1)

您必须将最后三个结果存储在三个变量中,然后对这些变量应用公式。您可以在下面找到使用int的简化示例。您可以使用BigInteger来增强此代码,使其同样适用于更大的数字。

static int compute_iterative(int n) {
    if (n == 0) return 1;
    if (n == 1) return 3;
    if (n == 2) return 5;

    int a_n3 = 1;
    int a_n2 = 3;
    int a_n1 = 5;
    int a_n = a_n1;
    int i = 3;
    while (i <= n) {
        a_n = a_n1 * (int) Math.pow(a_n2, 2) * (int) Math.pow(a_n3, 3);
        a_n3 = a_n2;
        a_n2 = a_n1;
        a_n1 = a_n;
        i++;
    }
    return a_n;
}

使用BigInterger的版本:

static BigInteger compute_iterative(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("Unsupported input value: " + n);
    }
    final BigInteger[] values = { BigInteger.valueOf(1), BigInteger.valueOf(3), BigInteger.valueOf(5) };
    if (n < values.length) {
        return values[n];
    }
    int i = 3;
    while (i <= n) {
        final BigInteger result = values[2].multiply(values[1].pow(2)).multiply(values[0].pow(3));
        values[0] = values[1];
        values[1] = values[2];
        values[2] = result;
        i++;
    }
    return values[2];
}
相关问题