http://poj.org/problem?id=2413

本文介绍了一种计算指定范围内Fibonacci数数量的方法。通过字符串处理实现大整数加法,进而生成Fibonacci数列,并比较输入范围来确定符合要求的Fibonacci数个数。
How many Fibs?
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10543 Accepted: 3910

Description

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<=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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值