public class Fibonacci{ public static long F(long n){ System.out.println("call F" + n); if (n == 0) return 0; if (n == 1) return 1; long t = F(n-1) + F (n-2); System.out.println("return " + t); return t; } public static void main(String[] args) { long N = Long.parseLong(args[0]); System.out.println(N+"th Fibonacci number is " + F(N)); } }
实验结果
java Fibonacci 4 call F4 call F3 call F2 call F1 call F0 return 1 call F1 return 2 call F2 call F1 call F0 return 1 return 3 4th Fibonacci number is 3