基本的Java递归方法 [英] Basic Java Recursion Method
问题描述
我在java中遇到这个基本的递归问题很麻烦;任何指针都会很棒。
I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.
编写一个静态递归方法来打印出
几何序列的第n项:2 ,6,18,54。
"Write a static recursive method to print out the nth term of the geometric sequence: 2, 6, 18, 54."
从我可以收集到的,在代码中的某处,我应该递归地将某些东西乘以3,但我正在努力弄清楚如何做到这一点。我知道我需要终止声明,但什么时候发生?我需要辅助方法吗?
From what I can gather, somewhere in the code I should be recursively multiplying something by 3, but I'm struggling to figure out how to do this. I know I need a termination statement, but when does that occur? Do I need a helper method?
推荐答案
A 递归函数是一个函数,其实现引用自身。下面是一些有趣的例子:
A Recursive Function is a function whose implementation references itself. Below is some funny example:
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问题)。 class适用于所有类型/数字:
The above class uses "int", which is good only for small numbers (because of Integer Overflow problem). The below class is better for all types/numbers:
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")));
}
}
这篇关于基本的Java递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!