Fibonacci數列的遞推公式爲:Fn=Fn-1+Fn-2,其中F1=F2=1。
當n比較大時,Fn也非常大,現在我們想知道,Fn除以10007的餘數是多少。
說明:在本題中,答案是要求Fn除以10007的餘數,因此我們只要能算出這個餘數即可,而不需要先計算出Fn的準確值,再將計算的結果除以10007取餘數,直接計算餘數往往比先算出原數再取餘簡單。
使用三個變量,每次循環根據前兩個變量得到第三個的值,然後將第二、三個變量的值分別賦值給第一個和第二個,然後再根據前兩個變量得到第三個的值,如此往復。
import java.util.Scanner;
class Main{//x爲要輸出的數字,f1,f2爲遞推公式的組成
public static void main(String[] args){
int f1 = 1;int f2 = 1;int x = 0;
int n = new Scanner(System.in).nextInt();
if(n == 1 || n == 2){
x = 1;
System.out.println(x);
}else{
for(int i = 3; i <= n; i++){
x = (f1 + f2)%10007;
f1 = f2;
f2 = x;
}
System.out.println(x);
}
}
}
或者用數組的方法將餘數存在數組中
import java.util.Scanner;
class Main{
public static void main(String[] args){
int[] str = new int[1000001];
str[1] = str[2] = 1;
int n = new Scanner(System.in).nextInt();
if(n == 1|| n == 2){
System.out.println(str[n]);
}else{
for(int i = 3; i <= n; i++){
str[i] = (str[i-1] + str[i-2])%10007;
}
System.out.println(str[n]);
}
}
}