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 <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
string add(string x,string y) //大数相加法
{
int i,temp,m=0;
string Fib;
int lenx=x.length();
int leny=y.length(); //返回字符串x,y的长度
if (lenx<leny) //如果x比y短
{
for (i=1; i<=leny-lenx; i++) //在x前面补0至与y相同的长度
x="0"+x;
}
else //反之
{
for (i=1; i<=lenx-leny; i++) //在y前面补0至与x相同的长度
y="0"+y;
}
lenx = x.length(); //x长度发生变化,需要重新返回长度
for (i=lenx-1; i>=0; i--)
{
temp=x[i]-'0'+y[i]-'0'+m; //相同位置的数字相加并加上后一位进的数
m=temp/10; //前一位将要加上m
temp%=10; //取余
Fib=char (temp+'0')+Fib; //将这一位的数放进新的字符串
}
if (m!=0)
Fib=char (m+'0')+Fib; //如果最高位的数大于10继续往前进
return Fib; //返回字符串
}
int main()
{
string fibs[1005],a,b;
int i;
fibs[1]="1";
fibs[2]="2";
for (i=3; i<1005; i++)
{
fibs[i]=add(fibs[i-2],fibs[i-1]); //将前1005个斐波那契数用数组统计。
}
while(cin >> a >> b)
{
if(a=="0" && b == "0")
break;
int head,end,len_a,len_b,len;
len_a = a.length(); //返回区间最小值的长度
len_b = b.length(); //返回区间最大值的长度
//找到区间内最小的斐波那契数的位置
for(i = 1; i<1005; i++)
{
len = fibs[i].length(); //返回某一斐波那契数的长度
if(len<len_a)
continue;
else if(len == len_a && fibs[i]>=a) //长度相等时比较字符串的大小
{
head = i;
break;
}
else if(len > len_a)
{
head = i;
break;
}
}
//找到区间内最大的斐波那契数的位置
for(i = 1004; i>=1; i--)
{
len = fibs[i].length();
if(len>len_b)
continue;
else if(len == len_b && fibs[i]<=b)
{
end = i;
break;
}
else if(len < len_b)
{
end = i;
break;
}
}
cout<<end-head+1<<endl; //首尾相减+1
}
return 0;
}
运行结果: