Java程序递归不起作用

时间:2016-05-20 16:07:13

标签: java math recursion

我正在努力制作一系列先前数字的数字 https://oeis.org/A004207

1,1,2,4,8,16,23,28,38,49,62,70,77,91,101,103,107,115,122,127,

这是我的代码

import java.math.BigInteger;
import java.util.ArrayList;
public class Problem {
        public static int getDigitSum(int number) {
            int total = 0;
            while ( number>0) {
                total +=  total + number%10;
                number = number /10;         


        }
      return total;
    }


    public static int getSum(int number) {
    if ((number == 0) || (number == 1)) // base cases
      return number;
    else
      // recursion step
      return getSum(getDigitSum(number - 1)) +  getSum(number - 2);
  } 

    public static void main( String s []) {
        int sum =0, difference=1, previous =1, last;
        //ArrayList <Integer> sum_list =  new ArrayList <Integer>();
        //sum_list.add(prevous);
        for (int i = 1; i<10; i++) {
            System.out.println(getSum(i));
        }
    }
}

此代码产生错误的输出

    1
1
2
3
5
8
13
21
34

1 个答案:

答案 0 :(得分:2)

很难说出你的代码到底出了什么问题,但它没有遵循公式:

  

对于n> 1,a(n)= a(n-1)+ a(n-1)的数字之和。

所以,您的代码应如下所示:

public static int getDigitSum(int number) {
    int total = 0;
    while (number > 0) {
        total += number % 10;
        number /= 10;
    }
    return total;
}

public static int getSum(final int number) {
    if (number <= 1) {
        return 1;
    } else {
        final int sum = getSum(number - 1); // a(n-1) from formula
        return sum + getDigitSum(sum); // sum of digits of a(n-1) from formula
    }
}

所以,从0开始:

for (int i = 0; i <= 10; i++) {
    System.out.println(getSum(i));
}
你会看到:

1
1
2
4
8
16
23
28
38
49
62

您的代码存在两个主要问题:

  1. total += total + number%10; double sum
  2. getSum(number - 2)应使用-1