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<=10100. 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<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
string str[1005];
string add(string a,string b)
{
if(a.length()<b.length())//保证a比b长
{
string t=a;
a=b;
b=t;
}
for(int i=a.length()-1,j=b.length()-1;i>=0;i--,j--)//从个位开始加
{
if(j>=0)//b加完后a[i]不再改变
a[i]=char(a[i]+b[j]-'0');
if(a[i]-'0'>=10)//进位
{
a[i]=char((a[i]-'0')%10+'0');
if(i)
a[i-1]++;
else
a='1'+a;
}
}
return a;
}
int main()
{
string a,b;
str[1]="1";
str[2]="2";
for(int i=3;i<1005;i++)
str[i]=add(str[i-1],str[i-2]);
//cout<<str[1005]<<endl; 确定str数组的大小
int m,n,ans=0,a_length,b_length,length;//m是>=a的第一个位置,n是<=b的最后一个位置
while(cin>>a>>b)
{
a_length=a.length();
b_length=b.length();
if(a=="0"&&b=="0")
break;
int i=1;
while(i<1005)
{
length=str[i].length();
if(length>a_length)
{
m=i;
break;
}
else if(length==a_length&&str[i]>=a)
{
m=i;
break;
}
i++;
}
i=1004;
while(i>=0)
{
length=str[i].length();
if(length<b.length())
{
n=i;
break;
}
else if(length==b.length()&&str[i]<=b)
{
n=i;
break;
}
i--;
}
ans=n-m+1;
cout<<ans<<endl;
}
return 0;
}