我在java中遇到了这个基本的递归问题,任何指针都会很棒。基本Java递归方法
“编写一个静态递归方法来打印出 几何序列的第n项:2,6,18,54。”
从我可以收集的代码中的某处我应该递归地乘以3,但我正在努力弄清楚如何做到这一点。我知道我需要终止声明,但是什么时候发生?我需要辅助方法吗?
我在java中遇到了这个基本的递归问题,任何指针都会很棒。基本Java递归方法
“编写一个静态递归方法来打印出 几何序列的第n项:2,6,18,54。”
从我可以收集的代码中的某处我应该递归地乘以3,但我正在努力弄清楚如何做到这一点。我知道我需要终止声明,但是什么时候发生?我需要辅助方法吗?
A 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台)
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
}