基本的 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
}
}
}
以及解决您的问题的方法:
And the solution for your problem:
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",它只适用于小数(因为整数溢出问题).以下类更适合所有类型/数字:
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屋!