E - How Many Fibs?

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

veit sun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值