Java數組預處理實現費切那波數列

下面我們展示一段Java實現費切那波數列的代碼。有兩個特點,它將已經運算過的數存在數組中,從而避免了重複運算;還有采用的big integer來存儲,可存儲的數據更大。
import java.math.BigInteger;
import java.util.Scanner;

public class Experiment1
{
static BigInteger f[] = new BigInteger[200];

public static void main(String[]args)
{
    f[0]=new BigInteger("1");  
    f[1]=new BigInteger("2");
    for(int i=2;i<f.length;i++)
    {
        f[i]=new BigInteger("0");
    }
    Scanner scan=new Scanner(System.in);
    while(scan.hasNext())
    {
        int n=scan.nextInt();
        printFibonacciArray( n-1);
        System.out.println(f[n-1]);

    }
}
public static BigInteger printFibonacciArray(int n)
{//the first number, the second number,the totel fibonacci numbers   
     if(n==0)
     {
        return f[0];
     }
     else if(n==1)
         return f[1];
     else
     {
         if(f[n].compareTo(new BigInteger("0"))!=0)
             return f[n];
         else
         {
             f[n]=printFibonacciArray(n-1).add(printFibonacciArray(n-2));
             return f[n];
         }
     }



}   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章