22 一千位斐波那契数

斐波那契数列是按如下递归关系定义的数列:
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() ------表示数列中某个数的位数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值