Java實現Fibonacci取餘

Description
Fibonacci數列的遞推公式爲:Fn=Fn-1+Fn-2,其中F1=F2=1。

當n比較大時,Fn也非常大,現在我們想知道,Fn除以10007的餘數是多少。

Input
多組測試數據

輸入包含一個整數n。1 <= n <= 1,000,000。

Output
每組輸出一行,包含一個整數,表示Fn除以10007的餘數。

Sample Input
10
22

Sample Output
55
7704

package 第八次模擬;

import java.util.Scanner;

public class Demo12Fibonacci {
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	while(sc.hasNext()){
		
	
	int n = sc.nextInt();
	int []f = new int [n+2];
	int [] count=new int [n+2];
	f[1]=1;
	f[2]=1;
	for (int i = 3; i <=n; i++) {
		f[i]=(f[i-1]+f[i-2]);
		if(f[i]/10007>=1){
			f[i]%=10007; 
		}
		 
	}
	System.out.println(f[n]);
	
	}
	
 
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章