我需要编写一个递归方法来计算以下序列:
m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + 6/13 + .... + i/(2i + 1)
然后我需要编写一个程序来显示 m(i)
for i = 1,2,....10
。
我理解递归的基本思想,到目前为止我已经完成了 2 个程序,一个用于阶乘,一个用于斐波那契数列。这个问题把我难住了。
这就是我到目前为止所拥有的。
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(m(i));
}
}
public static double m(int i) {
if (i == 1)
return 1;
else
return ???;
}
最佳答案
首先,看起来您的基本情况已关闭 - 应该是 1/3(该系列中的第一个数字)。
对于您的其他情况,您应该返回添加到当前步骤的下一个步骤。根据您的系列,当前步骤是 i/(2i + 1)
。
public static double m(int i) {
if (i == 1) {
// Base case is 1 - return the first number in the series
return 1/3;
} else {
// Get the current step (ie the current iteration of m(i))
double curStep = i / (2.0 * i + 1.0);
// Return the current step plus the next step down
return curStep + m(i - 1);
}
}
关于java - 使用递归添加分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15911953/