以前用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]
自己写算法又比较难,但是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]