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].
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
#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;
}