Problem B: How many Fibs?
Recall the definition of the Fibonacci numbers:
f 1 := 1Given two numbers a and b , calculate how many Fibonacci numbers are in the range [ a , b ].
f 2 := 2
f n := f n-1 + f n-2 (n>=3)
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; }