uva 10183 - How Many Fibs?(Fibonacci)

Problem B: How many Fibs?

Recall the definition of the Fibonacci numbers:

f 1 := 1 
f 2 := 2 
f n :=  f n-1 +  f n-2     (n>=3)
Given two numbers  a  and  b , calculate how many Fibonacci numbers are in the range [ a , b ].

Input Specification

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 Specification

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 <string>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 1000;
string F[maxn] , a , b;

string add(string n1 , string n2){
    int len1 = n1.length() , len2 = n2.length() , carry = 0;
    string result;
    for(int i = len1-1 , j = len2-1; i >= 0 || j >= 0; i-- , j--){
        int sum = carry;
        if(i >= 0) sum += n1[i]-'0';
        if(j >= 0) sum += n2[j]-'0';
        carry = sum/10;
        sum = sum%10;
        result.push_back(char('0'+sum));
    }
    if(carry) result.push_back(char('0'+carry));
    reverse(result.begin() , result.end());
    return result;
}

void Fibonacci(){
    F[0] = "1";
    F[1] = "2";
    for(int i = 2; i < maxn; i++){
        F[i] = add(F[i-1] , F[i-2]);
    }
}

bool is_larger(string n1 , string n2){
    int len1 = n1.length() , len2 = n2.length();
    if(len1 > len2) return true;
    if(len1 < len2) return false;
    for(int i = 0; i < len1; i++){
        if(n1[i]-'0' > n2[i]-'0') return true;
        if(n1[i]-'0' < n2[i]-'0') return false;
    }
    return false;
}



int Binary_search(string num){
    int l = 0 , r = 1000;
    while(l < r){
        int mid = (l+r)/2;
        if(is_larger(F[mid] , num)){
            r = mid;
        }else{
            l = mid+1;
        }
    }
    return r;
}

void computing(){
    int l = Binary_search(a), r = Binary_search(b)-1;
    if(l > 0 && F[l-1] == a){
        l--;
    }
    printf("%d\n" , r-l+1);
}

int main(){
    Fibonacci();
    while(cin >> a >> b && (a != "0" || b != "0")){
        computing();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值