1. 程式人生 > >Java練習 SDUT-1132_斐波那契數列

Java練習 SDUT-1132_斐波那契數列

fib static import scrip scanner close 數據 ring 兩種方法

C/C++經典程序訓練2---斐波那契數列

Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description

編寫計算斐波那契(Fibonacci)數列的第n項函數fib(n)(n<40)。

數列:
f1=f2==1;
fn=fn-1+fn-2(n>=3)。

Input

輸入整數n的值。

Output

輸出fib(n)的值。

Sample Input

7

Sample Output

13

經典的斐波那契。
兩種方法:

用類(C裏的函數)

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n;
        n = cin.nextInt();
        System.out.println(f(n));
        cin.close();
    }
    public static int f(int x)
    {
        if(x==1||x==2)
            return 1;
        else
            return f(x-1) + f(x-2);
    }
}

這種方法有很明顯的缺陷,會進行大量的重復計算,如算5,會算4與3,4又會計算3與2,這樣3便被計算了兩次,所以數據大一點就會超時。

所以可以用第二種方法,動歸思想,把每一步計算結果記錄下來。

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n,i;
        int a[] = new int[45];
        n = cin.nextInt();
        a[1] = a[2] = 1;
        for(i=3;i<=n;i++)
            a[i] = a[i-1] + a[i-2];
        System.out.println(a[n]);
        cin.close();
    }
}

Java練習 SDUT-1132_斐波那契數列