1599: Fibonacci Numbers
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 53 Solved: 23
[Submit][Status][Web Board]
Description
A Fibonacci sequence is calculated by adding the previous two members of the sequence, with
the rst two members being both 1.
f(1) = 1; f(2) = 1; f(n > 2) = f(n 1) + f(n 2)
Input
Your task is to take a number as input, and print that bonacci number.
Output
print that bonacci number.
Sample Input100
Sample Output354224848179261915075
1 import java.math.BigDecimal;
2 import java.util.Scanner;
3
4 public class fab {
5 /*
6 * 首先用保留字class來申明一個新的類,而且是公用的類
7 */
8
9 public static void main(String args[]) {
10 /*
11 * 在該類中定義了方法main,其中public 表示許可權, 公用的,static
12 * 如果一個成員被聲明為static,它就能夠在它的類的任何對象建立之前 被訪問,而不必引用任何對象。你可以將方法和變數都聲明為static。
13 * static 成員的最常見的例子是main( ) 。因為在程式開始執行時 必須調用main() ,所以它被聲明為static。 void
14 * 是指main函數傳回值為空白
15 */
16 Scanner cin = new Scanner(System.in);
17 /*
18 * Scanner--控制台輸入 Scanner類是JDK5新添加的一個類,主要作用是處理輸入資料流、檔案和常值內容等 。
19 */
20 int n, i;
21 BigDecimal f[] = new BigDecimal[6000];
22 /*
23 * 動態初始化 *
24 * 動態初始化,也就是只為數組指定長度,並且在記憶體中申請空間。動態初始化可以不必和數組的聲明放在一起,也可以重新初始化一個初始化的數組。
25 * 動態初始化的文法格式:資料類型 數組名稱[ ] = new 資料類型[長度]
26 */
27 f[1] = BigDecimal.valueOf(1);
28 f[2] = BigDecimal.valueOf(1);
29 /*
30 * 對大數的賦值
31 */
32 for (i = 3; i <= 5000; i++)
33 f[i] = f[i - 1].add(f[i - 2]);
34 while (cin.hasNext()) {
35 /*
36 * 等同於!=EOF
37 */
38 n = cin.nextInt();
39 System.out.println(f[n]);
40
41 }
42 }
43
44 }