【发布时间】:2012-02-08 19:22:38
【问题描述】:
我在java中的这个基本递归问题上遇到了很多麻烦;任何指针都会很棒。
"写一个静态递归方法打印出第n项 等比数列:2、6、18、54。"
据我所知,在代码中的某处,我应该递归地将某个值乘以 3,但我正在努力弄清楚如何做到这一点。我知道我需要终止声明,但是什么时候会发生呢?我需要辅助方法吗?
【问题讨论】:
我在java中的这个基本递归问题上遇到了很多麻烦;任何指针都会很棒。
"写一个静态递归方法打印出第n项 等比数列:2、6、18、54。"
据我所知,在代码中的某处,我应该递归地将某个值乘以 3,但我正在努力弄清楚如何做到这一点。我知道我需要终止声明,但是什么时候会发生呢?我需要辅助方法吗?
【问题讨论】:
Recursive Function 是一个其实现引用自身的函数。下面是一个有趣的例子:
public class Inception {
public void dream() {
boolean enoughDreaming = false;
//Some code logic below to check if it's high time to stop dreaming recursively
...
...
if(!enoughDreaming) {
dream(); //Dream inside a Dream
}
}
}
您的问题的解决方案:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(5, 1, 2));
}
public static int findNthNumber(int n, int count, int res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res *3);
}
}
编辑:
上面的类使用“int”,它只适用于小数字(因为整数溢出问题)。下面的类更适合所有类型/数字:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(2000, 1, new BigInteger("2")));
}
public static BigInteger findNthNumber(int n, int count, BigInteger res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));
}
}
【讨论】:
这是最简单的递归示例。
你需要一个方法声明。
你需要检查是否已经到达终点。
否则,您需要再次调用该方法,并使用一个操作来区分一个术语和下一个术语。
【讨论】:
是的,您需要一个终止条件 - 基本上是当您采取了尽可能多的步骤时。因此,请考虑您希望如何从一个呼叫转换到另一个呼叫:
【讨论】:
这是一个 C# 示例(我知道你在使用 Java,但它非常相似)
public static void Recursive(int counter, int iterations, int value, int multiplier)
{
if (counter < iterations)
{
Console.WriteLine(value);
counter++;
Recursive(counter, iterations, (value * multiplier), multiplier);
}
}
所以当你运行函数时你输入参数
每次运行时,它都会检查计数器是否小于迭代次数。如果大于,则打印该值,计数器递增,该值乘以乘数,然后将相同的参数添加回函数中。
【讨论】:
递归解法:Seq(1) 是序列的第一个元素 .... Seq(n-th)
public static void main(String args[]) throws Exception {
int x = Seq(3); //x-> 18
}
public static int Seq(int n){
return SeqRec(n);
}
private static int SeqRec(int n){
if(n == 1)
return 2;
else return SeqRec(n - 1) * 3;
}
非递归解决方案:
public static int Non_RecSeq(int n){
int res = 2;
for(int i = 1; i < n; i ++)
res *= 3;
return res;
}
public static void main(String args[]) throws Exception {
int x = Non_RecSeq(3); //x-> 18
}
【讨论】: