1022. Fib數列

https://acm.sjtu.edu.cn/OnlineJudge/problem/1022

Description
定義Fib數列:
1
,
1
,
2
,
3
,
5
,
8
,
13
,
…
求第
N
項除以
2010
的餘數

Input Format
輸入僅一行,爲一個整數
N
Output Format
輸出僅一行,爲第
N
項除以
2010
的餘數

Sample Input
3
Sample Output
2
Limits:
對於70%的數據 
N
≤
1
,
000
,
000
對於100%的數據 
N
≤
210
,
000
,
000
,
000

N%2010的fib數列的週期是2040

import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
public class Main{
	static ArrayList<Integer> list = new ArrayList<>();
	public static void main(String[] args) {
		try {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		String str = br.readLine();
    		BigInteger n = new BigInteger(str);	
    		int a = 1;
    		int b = 1;
    		int len = Integer.parseInt(n.remainder(new BigInteger("2040")).toString());
    		for(long i = 3; i <= len; i++) {
    			int tmp = b;
    			b = (a + b)%2010;
    			a = tmp;
    		}
    		if(str.contentEquals("1")) System.out.println(1);
    		if(str.contentEquals("2")) System.out.println(2);
    		else System.out.println(b);
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}

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