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]);
}
}
}