問(wèn)題描述
Fibonacci數(shù)列的遞推公式為:Fn=Fn-1+Fn-2彭沼,其中F1=F2=1。
當(dāng)n比較大時(shí)备埃,F(xiàn)n也非常大姓惑,現(xiàn)在我們想知道,F(xiàn)n除以10007的余數(shù)是多少按脚。
輸入格式
輸入包含一個(gè)整數(shù)n于毙。
輸出格式
輸出一行,包含一個(gè)整數(shù)辅搬,表示Fn除以10007的余數(shù)唯沮。
樣例輸入
10
樣例輸出
55
樣例輸入
22
樣例輸出
7704
數(shù)據(jù)規(guī)模與約定
1 <= n <= 1,000,000。
算法思路:
因?yàn)镕n=Fn-1+Fn-2堪遂,所以我們可以理解為n角標(biāo)的元素等于前一個(gè)角標(biāo)和前兩個(gè)角標(biāo)的值之和,new一個(gè)int[ ]數(shù)組,初始化0和1角標(biāo)的值為1,當(dāng)輸入的整數(shù)為1或2時(shí),直接輸出答案 1 ,輸入不為1或2時(shí),則進(jìn)行for循環(huán),每次循環(huán)將前兩個(gè)值加起來(lái)等于目標(biāo)的值,再%10007得到余數(shù)存入int數(shù)組中
法一
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
int[] array = new int[1000000];
array[0] = array[1] = 1;
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
if (x == 1 || x == 2) {
System.out.println(1);
} else {
for (int y = 2; y < x; y++) {
array[y] = (array[y - 1] + array[y - 2]) % 10007;
}
System.out.println(array[x - 1]);
}
}
}
法二
public class Fibonacci數(shù)列_方法二 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int f1 = 1;
int f2 = 1;
int x = scanner.nextInt();
if (x == 1 || x == 2) {
System.out.println(1);
} else {
for (int y = 3; y <= x; y++) {
int temp = f2;
f2 = (f1 + f2)%10007;
f1 = temp;
}
System.out.println(f2);
}
}
}