首页 > 编程语言 > 详细

UVA10183 - How Many Fibs?(java大数+二分)

时间:2014-12-03 23:21:37      阅读:359      评论:0      收藏:0      [点我收藏+]

UVA10183 - How Many Fibs?(java大数+二分)

题目链接

题目大意:给你a,b,求[a,b]之间有多少个fibs数。

解题思路:虽然a.b很大,但是在10^100内的fibs却不超过500个。这样就可以先把这些fibs保存在数组中,然后每次二分去找a,b的位置,然后就可以得到之间有多少个fibs。

代码:

import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.String.*;

public class Main {

    static BigInteger f[] = new BigInteger[10005];
    static int n = 2;
    public static void init () {

        f[1] = BigInteger.valueOf(1);
        f[2] = BigInteger.valueOf(2);
        BigInteger c = BigInteger.valueOf(10).pow(100);

        for (int i = 3; f[i - 1].compareTo(c) != 1; i++) {
            f[i] = f[i - 1].add(f[i - 2]);
            n++;
        }
    }

    public static int upper_bound(BigInteger a) {

        int l = 1;
        int r = n;
        int m, num;

        while (l < r) {
            m = (l + r) / 2;
            num = a.compareTo(f[m]);
            if (num <= 0)
                r = m;
            else
                l = m + 1;
        }
        return r;         
    }

    public static void main(String args[]) {

        Scanner cin = new Scanner(System.in);
        init();

        BigInteger a, b;
        while (cin.hasNext()) {

            a = cin.nextBigInteger();
            b = cin.nextBigInteger();
            if (a.equals(BigInteger.ZERO) && b.equals(BigInteger.ZERO))
                break;
            int x = upper_bound(b);
            int y = upper_bound(a) - 1;

            if (f[x].compareTo(b) != 0)
                x--;
            System.out.println(x - y);                
        }
    }
}

UVA10183 - How Many Fibs?(java大数+二分)

原文:http://blog.csdn.net/u012997373/article/details/41706917

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!