我在使用Java这个基本递归问题时遇到了很多麻烦; 任何指针都很棒。
"Write a static recursive method to print out the nth term of the
geometric sequence: 2, 6, 18, 54."
据我所知,我应该在代码中的某个地方递归地将某物乘以3,但我一直在努力寻找方法。 我知道我需要终止声明,但是何时发生? 我需要帮手方法吗?
递归函数是其实现引用自身的函数。以下是一些有趣的示例:
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",它仅对少量数字有效(由于Integer Overflow问题)。下面的类对所有类型/数字都更好:
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")));
}
}
这是递归的最简单的例子。
您需要一个方法声明。
您需要检查是否已达到终点。
否则,您需要使用一个运算来再次调用该方法,该运算会使得一个术语与下一个术语有所不同。
递归解决方案: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
}
这是一个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);
}
}
因此,当您运行函数时,请输入参数
首次调用" counter"时始终为0
"迭代次数"是n的值
在您的情况下,"值"是您的初始值2
"乘数"是您希望每次迭代乘以多少,在您的情况下为3
每次运行时,它都会检查计数器是否小于迭代次数。如果更多,则输出该值,计数器递增,将该值乘以乘数,然后将相同的参数加回到函数中。
是的,您需要终止条件-基本上是在您按照需要执行了许多步骤之后。因此,请考虑如何从一个呼叫过渡到另一个呼叫:
到目前为止,您将如何传播结果?
您需要什么额外的状态来跟踪需要执行的更多步骤?
您将从该方法返回什么?