斐波那契数列是按如下递归关系定义的数列:
F1 = 1
F2 = 1
Fn = Fn−1 + Fn−2
第1项是1,第2项是1。这个数列从第3项开始,每一项都等于前两项之和。
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987, 1597,2584,4181,6765,10946,17711,28657,46368
在斐波那契数列中,第一个有三位数字的项是第12项F12。
求第一个有1000位数字的是第几项?
output: 4782
分析:1000位的数字要用 BigInteger 计算
/**
*计算斐波那契数列 Fibonacci()
*
* @param limit 需要几位的数字(1000)
* @param count 记录是斐波那契数列的第几项
* @return 是斐波那契数列中的第几项
* **/
public static int Fibonacci(int limit) {
BigInteger n1 = new BigInteger("1"); //定义变量first 并赋值为1
BigInteger n2 = new BigInteger("1"); //定义变量second 并赋值为1
int count = 3; //记录是第几项
for(int i=3; i<Integer.MAX_VALUE; i++) {
BigInteger num = n1.add(n2);
if(num.toString().length() >= limit) {
break;
}
n1 = n2;
n2 = num;
count ++;
}
return count;
}
public static void main(String[] args) {
System.out.println(Fibonacci(1000));
}
**num.toString().length() ------表示数列中某个数的位数