Java中的递归斐波那契方法
斐波那契数列是一个序列,其中每个数字是前两个数字的和。斐波那契数列中特定位置的数字可以使用递归方法获得。
演示此过程的程序如下:
示例
public class Demo {
public static long fib(long n) {
if ((n == 0) || (n == 1))
return n;
else
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
System.out.println("The 0th fibonacci number is: " + fib(0));
System.out.println("The 7th fibonacci number is: " + fib(7));
System.out.println("The 12th fibonacci number is: " + fib(12));
}
}输出结果
The 0th fibonacci number is: 0 The 7th fibonacci number is: 13 The 12th fibonacci number is: 144
现在让我们了解上面的程序。
该方法fib()计算位置n处的斐波那契数。如果n等于0或1,则返回n。否则,它将递归调用自身并返回fib(n-1)+fib(n-2)。演示此代码段如下:
public static long fib(long n) {
if ((n == 0) || (n == 1))
return n;
else
return fib(n - 1) + fib(n - 2);
}在中main(),fib()使用不同的值调用该方法。演示此代码段如下:
public static void main(String[] args) {
System.out.println("The 0th fibonacci number is: " + fib(0));
System.out.println("The 7th fibonacci number is: " + fib(7));
System.out.println("The 12th fibonacci number is: " + fib(12));
}热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短