2013
11-11

# 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].

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.

For each test case output on a single line the number of Fibonacci numbers fi with a<=fi<=b.

10 100
1234567890 9876543210
0 0


5
4


import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;

/**
*
* poj2413
* @author NC
*/
public class Main {

public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while (scan.hasNext()) {
BigInteger a = scan.nextBigInteger();
BigInteger b = scan.nextBigInteger();
if (a.compareTo(BigInteger.ONE) == -1 && b.compareTo(BigInteger.ONE) == -1) {
break;
}
int count = 0;
BigInteger[] f = new BigInteger[1000000];
f[0] = BigInteger.ONE;
for (int i = 0; i < f.length; i++) {
if (i >= 2) {
f[i] = f[i - 1].add(f[i - 2]);
}
if (f[i].compareTo(b)==1) {
break;
}
if (!(f[i].compareTo(a)==-1)) {
count++;
}
}
System.out.println(count);
}
}
}

1. 第一题是不是可以这样想，生了n孩子的家庭等价于n个家庭各生了一个1个孩子，这样最后男女的比例还是1:1

2. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？