我在java中遇到这个基本的递归问题很麻烦; 任何指针都会很棒.
"编写一个静态递归方法来打印出几何序列的第n项: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
}
}
}
Run Code Online (Sandbox Code Playgroud)
并为您的问题的解决方案:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
上面的类使用"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")));
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13973 次 |
最近记录: |