使用BigInteger求Fabonacci数

以前用c求斐波那契数,如果要求第n位时,n是个比较大的数,long类型无法存储,发生越界.
自己写算法又比较难,但是java提供了BigInteger这个类,这样就可以避免越界了,相信底层也是很难的算法,一提到算法就有点恐惧.

代码如下:
import java.io.*;
import java.math.*;
public class Fibonacci
{
public static void main(String[] args)
{
long start=System.currentTimeMillis();
System.out.println("查找第几个斐波那契额数::");
int number=1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
number=Integer.parseInt(br.readLine());
}catch(Exception e){
e.printStackTrace();
}
long end=System.currentTimeMillis();
System.out.println("结果:"+fibonacci(number));
System.out.println("花费:"+(end-start)+"ms");
}

public static BigInteger fibonacci(int n)
{
BigInteger f1=new BigInteger("1");
BigInteger f2=new BigInteger("1");
BigInteger result=new BigInteger("1");
if(n==1||n==2)
{
return f1;
}
else
{
for(int i=3;i<=n;i++)
{
result=f1.add(f2);
f1=f2;
f2=result;
}
return result;
}

}
}

结果:
[img]http://dl.iteye.com/upload/attachment/350608/743efc0f-8722-31b4-906d-2c9efb6afbd0.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值