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
我们先来里个思路:
首先我们可以用牺牲空间来节省时间的方法,把斐波那契数的每一个数的每一位存放在二位数组之中
然后我们想要计算两个数之间有多少个斐波那契数,我们就需要比较数的长度,和字典序的大小
以此我们想到,我们还需要把一开始存放斐波那契数的二维数组变成字符,目的是可以用字符串比较函数来比较字典序的大小
不多说上代码:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int f[605][1000];
char num[605][1000];
int main(){
memset(f,0,sizeof(f));
memset(num,0,sizeof(num));
f[1][0]=1;
f[2][0]=2;
f[3][0]=3;
int flagi=0;
for(int i=4;i<605;i++){
for(int j=0;j<501;j++){
int sum=f[i-1][j]+f[i-2][j]+flagi;
if(sum>9){
flagi=1;
}
else{
flagi=0;
}
f[i][j]=sum%10;
}
}
int flag=0;
int k=0;
for(int i=1;i<605;i++){
flag=0;
k=0;
for(int j=500;j>=0;j--){
if(f[i][j]!=0){
flag=1;
}
if(flag!=0){
num[i][k++]=f[i][j]+'0';
}
}
num[i][k]='\0';
}
char m[605];
char n[605];
while(~scanf("%s %s",m,n)){
if(m[0]=='0'&&n[0]=='0'){
break;
}
int sum=0;//sum是来计算总斐波那契数的个数
int lenm=strlen(m);
int lenn=strlen(n);
for(int i=1;i<=500;i++){
if(strlen(num[i])>lenm&&strlen(num[i])<lenn){
sum++;//数的长度在m,n长度之间,一定满足题意
}
else if(lenm==lenn&&strlen(num[i])==lenn){
if(strcmp(num[i],m)>=0&&strcmp(num[i],n)<=0){
sum++;
}
}
else if(strlen(num[i])==lenm){
if(strcmp(num[i],m)>=0){
sum++;
}
}
else if(strlen(num[i])==lenn){
if(strcmp(num[i],n)<=0){
sum++;
}
}
}
cout<<sum<<endl;
}
return 0;
}