一个递归函数是一个函数,它的实现引用自身。以下是一些有趣的示例:
public class Inception { public void dream() { boolean enoughDreaming = false; //Some pre 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"))); }}


