您的位置:首页 > 其它

hdu1316 How Many Fibs?

2014-04-08 20:14 441 查看

How Many Fibs?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 3613    Accepted Submission(s): 1451


[align=left]Problem Description[/align]
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].

 

[align=left]Input[/align]
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 <= 10^100. The numbers a and b are given with no superfluous leading zeros.

 

[align=left]Output[/align]
For each test case output on a single line the number of Fibonacci numbers fi with a <= fi <= b.

 

[align=left]Sample Input[/align]

10 100
1234567890 9876543210
0 0

 

[align=left]Sample Output[/align]

5
4

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.StreamTokenizer;
import java.util.StringTokenizer;
import java.io.IOException;
import java.math.BigInteger;

class Main
{
public static final boolean DEBUG = false;
public StringTokenizer tokenizer;
public PrintWriter cout;
BufferedReader cin;

public void init() throws IOException
{
if (DEBUG) {
cin = new BufferedReader(new FileReader("d:\\OJ\\uva_in.txt"));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}
tokenizer = new StringTokenizer("");

cout = new PrintWriter(new OutputStreamWriter(System.out));

}

public String next() throws IOException
{
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(cin.readLine());
}

return tokenizer.nextToken();
}

public void solve(String a, String b)
{
BigInteger ba = new BigInteger(a);
BigInteger bb = new BigInteger(b);
BigInteger f1 = BigInteger.ONE;
BigInteger f2 = BigInteger.valueOf(2);

BigInteger tmp;
while (true) {
tmp = f1.add(f2);

if (f1.compareTo(ba) >= 0) break;
f1 = f2;
f2 = tmp;
}

BigInteger ans = BigInteger.ZERO;
while (true) {
tmp = f1.add(f2);
if (f1.compareTo(bb) > 0) break;
ans = ans.add(BigInteger.ONE);
f1 = f2;
f2 = tmp;
}

cout.println(ans.toString());
cout.flush();
}

public static void main(String[] args) throws IOException
{
Main solver = new Main();
solver.init();
String a, b;

while (true) {
a = solver.next();
b = solver.next();
if ("0".equals(a) && "0".equals(b)) break;
solver.solve(a, b);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: