斐波那契數列:
斐波那契數列指的是這樣一個數列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........
這個數列從第3項開始,每一項都等于前兩項之和,
代碼:
以下是用java代碼實作的斐波那契數列的遞回與非遞回演算法
package com.bug1; public class Main { public static void main(String[] args) { System.out.println("遞回實作斐波那契數列"); System.out.println(fib(4)); System.out.println("非遞回實作斐波那契數列"); System.out.println(fib2(4)); } /* * n= 1 2 3 4 5 6 7 * sum= 1 1 2 3 5 8 * * */ //遞回實作斐波那契數列 public static int fib(int n) { if(n<=2)return 1; return fib(n-1)+fib(n-2); } //非遞回實作斐波那契數列 public static int fib2(int n) { if(n<=2)return 1; int first=1; int second=1; int sum=0; while(n>2) { sum=first+second; first=second; second=sum; n--; } return second; } }
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/115742.html
標籤:其他
上一篇:選擇排序
