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 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志