高精度问题——Java大数类~系列6——Fibonacci数 hdu 1316 hdu 1715
高精度问题(6)——Fibnacci数
Fibonacci数列,像Catalan数列一样,增长速度都很快。hdu上有两道相关的题目,一个是统计一个区间内fib数的个数,另一个是输出第n个fib数,实际上都是差不多的,用Java大数类就好了。
首先是1316题目意思很简单,就是统计在一个区间内,Fibonacci数的个数。但是值得注意的是,区间范围上限可以达到10100,所以一般的数据类型是不行的,用Java大数类就很好解决了。
hdu 1316 原题如下:
How Many Fibs?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3095 Accepted Submission(s): 1229
Problem 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].
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 <= 10^100. 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 //6.fibonacci之区间计数 ~java~ hdu 1316 2 import java.math.BigInteger; 3 import java.util.Scanner; 4 import java.io.*; 5 6 public class Main 7 { 8 public static void main(String[] args) 9 { 10 Scanner cin = new Scanner(System.in); 11 int i, j; 12 BigInteger a, b; 13 BigInteger f[]=new BigInteger[501]; 14 BigInteger zero=new BigInteger("0"); 15 f[1]=new BigInteger("1"); 16 f[2]=new BigInteger("2"); 17 for(i=3;i<=500;i++) 18 f[i]=f[i-1].add(f[i-2]); 19 while(cin.hasNextBigInteger()) 20 { 21 a=cin.nextBigInteger(); 22 b=cin.nextBigInteger(); 23 if(a.compareTo(zero)==0 && b.compareTo(zero)==0) 24 break; 25 for(j=0,i=1;i<=500;i++) 26 { 27 if(a.compareTo(f[i])<=0 && b.compareTo(f[i])>=0) 28 j++; 29 if(b.compareTo(f[i])<0) break; 30 } 31 System.out.println(j); 32 } 33 } 34 }
其次是1715,原理和上面一样,没什么要特别注意的地方。
hdu 1715 原题如下:
大菲波数
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8541 Accepted Submission(s): 2881
Problem Description
Fibonacci数列,定义如下:
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
Input
输入第一行为一个整数N,接下来N行为整数Pi(1<=Pi<=1000)。
Output
输出为N行,每行为对应的f(Pi)。
Sample Input
5
1
2
3
4
5
Sample Output
1
1
2
3
5
代码如下:
1 //6.大fibonacci数 ~java~ hdu 1715 2 import java.math.BigInteger; 3 import java.util.Scanner; 4 import java.io.*; 5 6 public class Main 7 { 8 public static void main(String[] args) 9 { 10 Scanner cin = new Scanner(System.in); 11 int i, j, t; 12 BigInteger f[]=new BigInteger[1001]; 13 f[1]=new BigInteger("1"); 14 f[2]=new BigInteger("1"); 15 for(i=3;i<=1000;i++) 16 f[i]=f[i-1].add(f[i-2]); 17 while(cin.hasNextInt()) 18 { 19 t=cin.nextInt(); 20 for(i=1;i<=t;i++) 21 { 22 j=cin.nextInt(); 23 System.out.println(f[j]); 24 } 25 } 26 } 27 }
2013-08-11
晴
浙公网安备 33010602011771号