Wannafly挑戰賽9 C 列一列

Wannafly挑戰賽9 C 列一列

原題地址:https://www.nowcoder.com/acm/contest/71/C

思路

一道求斐波那契數列第K項的題目。一開始的想法是直接打表打到100000,然後用二分查找來找位置,但突然發現我太天真了,別說第100000位的斐波那契數,哪怕是第1000位都已經精度溢出了,所以只能用hash,在打表的時候用一個很大的素數對每一次相加進行取模運算,這樣就可以保證不會出現精度溢出了,且基本不會出現取模運算後相同的結果。

AC代碼

import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 *
 * @author wanyu
 * @Date: 2018-02-13
 * @Time: 22:33
 * To change this template use File | Settings | File Templates.
 * @desc
 */
public class Main {

    private static long mod = 177777777;//使用一個極大的素數用來取模運算
    private static long[] nums = new long[100010];

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedInputStream(System.in));
        fab();
        while (in.hasNext()) {
            String s = in.nextLine();
            BigInteger temp = new BigInteger(s);
            int n = temp.mod(BigInteger.valueOf(mod)).intValue();
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == n) {
                        System.out.println(i);
                    break;
                }
            }
        }
    }

    private static void fab() {
        nums[0] = 1;
        nums[1] = 1;
        for (int i = 2; i <= 100000; i++) {
            nums[i] = (nums[i - 2] + nums[i - 1]) % mod;//取模運算
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章