How many Fibs?
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10543 | Accepted: 3910 |
Description
Recall the definition of the Fibonacci numbers:
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<=10100. 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
注意:数列是1,2,3,。。。
不是1,1,2,3,。。
代码:
#include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; char fib[505][150]; char a[150]; char b[150]; char temp[150]; char *add() { int maxn = strlen(b); int c = 0; int sum = 0; int l1 = (int)strlen(a); for (int i = 0; i < maxn; i ++) { sum = 0; if (i < l1) { sum += a[i] - '0'; } sum += b[i] - '0'; sum += c; c = sum / 10; temp[i] = sum % 10 + '0'; } while (c!=0) { temp[maxn ++] = c%10+'0'; c/=10; } temp[maxn] = '\0'; return temp; } void init() { strcpy(fib[0], "1"); strcpy(fib[1], "2"); for (int i = 2; i < 505; i ++) { strcpy(a, fib[i-2]); strcpy(b, fib[i-1]); add(); strcpy(fib[i], temp); } for (int i = 0; i < 505; i ++) { reverse(fib[i], fib[i] + strlen(fib[i])); } } int ab_compare(char *s1, char *s2) { int l1 = strlen(s1); int l2 = strlen(s2); if (l1 != l2) { if (l1 > l2) return 1; else return -1; } for (int i = 0; i < l1; i ++) { if (s1[i] > s2[i]) return 1; else if (s1[i] < s2[i]) return -1; } return 0; } int main() { init(); while (scanf("%s%s", a, b)!=EOF) { if (b[0] == '0') break; int ans = 0; for (int i = 0; i <= 505; i ++) { if (ab_compare(fib[i], a) >= 0 && ab_compare(fib[i], b) <= 0) ans ++; } printf("%d\n", ans); } return 0; }