藍橋網試題 java 入門訓練 Fibonacci數列


 

----------------------------------------------------------------------------------------------------------------------------------------------

自己的理解: 

因為數據模型與約定給定的范圍很大,所以在我們用Fibonacci數列去寫算法的時候很可能會

讓我們定義的int變量超出范圍,就是我們的算法沒有考慮的很全面,在說明中,已經很明顯得的

給了我們一個提示 "Fn會很大,直接計算余數往往比先算出原數再取余簡單。"

-----------------------------------------------------------------------------------------------------------------------------------------------------

 算法一:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
    	int[] a = new int[10000001];
    	a[1] = 1;
    	a[2] = 1;
        int n = new Scanner(System.in).nextInt();
        for (int i=3; i<=n; i++){
        	a[i] = (a[i-1]+a[i-2])%10007;
        }
        System.out.println(a[n]);
    }
}

  算法二:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int f1 = 1;
        int f2 = 1;
        int n = new Scanner(System.in).nextInt();
        for (int i=3; i<=n; i++){
        	int t = f2;
        	f2 = (f1 + f2) % 10007;
            f1 = t;
        }
        System.out.println(f2);
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM