解法不一定是最有效率、最低複雜度、最佳效能的,完全是依照自己的想法做!
---
先來個暖身吧...
費氏數列範例:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.....
從以上數列可以觀察到,從第三個數字開始,其值為前兩個數字的相加。
即:2 = 1+1; 3 = 2 + 1; .........
即:Fn = F(n-1) + F(n-2);
假設題目要求:給一數字N,求費氏數列中第N數的值
構想:N = 1 or 2時,直接輸入Ans = 1; 若N >=3,則進入迴圈判斷計算(N=3 to N),利用兩個變數儲存 N-1 與 N-2 的值,程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Fibonacci { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
int number = 0; | |
Scanner scanner = new Scanner(System.in); | |
System.out.println("Enter a number: "); | |
number = scanner.nextInt(); | |
if(number == 1) { | |
System.out.println("last Fibonacci num = 1"); | |
} else if(number == 2) { | |
System.out.println("last Fibonacci num = 1"); | |
} else { | |
int res = calculate(number); | |
System.out.println("last Fibonacci num = "+res); | |
} | |
} | |
private static int calculate(int num) { | |
// TODO Auto-generated method stub | |
int p1 = 1; //the first number in fibonacci | |
int p2 = 1; //the second number in fibonacci | |
int res = 0; | |
for(int i = 3; i <= num; i++) { | |
res = p1 + p2; | |
p1 = p2; | |
p2 = res; | |
} | |
return res; | |
} | |
} |