hdu 1316 二分+高精度

http://acm.hdu.edu.cn/showproblem.php?pid=1316

Problem Description
Recall the definition of the Fibonacci numbers: 
f1 := 1 
f2 := 2 
fn := fn-1 + fn-2 (n >= 3) 

Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a, b]. 
 

Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a and b. Input is terminated by a = b = 0. Otherwise, a <= b <= 10^100. The numbers a and b are given with no superfluous leading zeros.
 

Output
For each test case output on a single line the number of Fibonacci numbers fi with a <= fi <= b. 
 

Sample Input
  
  
10 100 1234567890 9876543210 0 0
 

Sample Output
  
  
5 4
二分找出比a小的第一个数和比b大的第一个数然后二者之差再减1就是答案。

#include <string.h>
#include <stdio.h>
#include <iostream>
#define M 105
using namespace std;
char data[1000][M+2];
char a[M+2],b[M+2];
int cmp_ab(char *s1,char *s2)
{
    for(int k=0;k<=105;k++)
    {
        if(k==105)
            return s1[k]-s2[k];
        if(s1[k]!=s2[k])
            return s1[k]-s2[k];
    }
}
int find1(int i,char *x)
{
    int low=0,high=i,mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        int value=cmp_ab(x,data[mid]);
        if(value>0)low=mid+1;
        if(value==0)return mid-1;
        if(value<0)high=mid-1;
    }
    return high;
}
int find2(int i,char *x)
{
    int low=0,high=i,mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        int value=cmp_ab(x,data[mid]);
        if(value>0)low=mid+1;
        if(value==0)return mid+1;
        if(value<0)high=mid-1;
    }
    return low;
}
int main()
{
    int i,j,p;
    data[0][105]=1;
    data[1][105]=2;
    i=2;p=105;
    while(data[i-1][5]<=1)
    {
        for(j=105;j>=p;j--)
        {
            data[i][j]=data[i-1][j]+data[i-2][j];
        }
        for(j=105;j>=p;j--)
        {
            int c=data[i][j]/10;
            if(c>=1)
            {
                data[i][j]=data[i][j]%10;
                data[i][j-1]=data[i][j-1]+c;
            }
        }
        if(data[i][p-1]>0)
            p--;
        i++;
    }
    while(cin >> a>> b)
    {
        if(a[0]=='0'&&b[0]=='0')break;
        int len1=strlen(a)-1;
        int len2=strlen(b)-1;
        int k;
        for(int d=len1,k=105;d>=0;d--,k--)
        {
            a[k]=a[d]-'0';
            a[d]=0;
        }
        for(int d=len2,k=105;d>=0;d--,k--)
        {
            b[k]=b[d]-'0';
            b[d]=0;
        }
        int lt=find1(i-1,a);
        int rt=find2(i-1,b);
        cout << rt-lt-1<<endl;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值