Java 算法訓練 斐波那契數列(高精度)

題目求斐波那契數列的第n位數

介紹:

斐波那契數列第一個和第二個數1,其他數是它前兩數之和,例如:
1、1、2、3、5、8、13、21、34、……等等

代碼如下:

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(fbnq(scanner.nextInt()));
    }
    static int fbnq(int n){
        if (n==1||n==2){
            return 1;
        }else {
            return  fbnq(n-1) + fbnq(n-2);
        }
    }

但是如果n=100時我們看看會有什麼情況:
在這裏插入圖片描述這裏直接卡住無法返回結果,說明計算的數太大了。

所以我們在這裏使用Biginteger這個 大數據類型

1.賦值:

BigInteger a=new BigInteger("1");
BigInteger b=BigInteger.valueOf(1);

2.運算:
① add(); 大整數相加

BigInteger a=new BigInteger(23); 
BigInteger b=new BigInteger(34); 

a. add(b);
②subtract(); 相減
③multiply(); 相乘
④divide(); 相除取整
⑤remainder(); 取餘
⑥pow(); a.pow(b)=a^b
⑦gcd(); 最大公約數
⑧abs(); 絕對值
⑨negate(); 取反數
⑩mod(); a.mod(b)=a%b=a.remainder(b);

3.BigInteger構造函數:
一般用到以下兩種:
BigInteger(String val);
將指定字符串轉換爲十進制表示形式;
BigInteger(String val,int radix);
將指定基數的 BigInteger 的字符串表示形式轉換爲 BigInteger
4.基本常量:

A=BigInteger.ONE 1 
B=BigInteger.TEN 10 
C=BigInteger.ZERO 0 
5.n.compareTo(BigInteger.ZERO)==0  // 相對於n=0
6.if(a[i].compareTo(n)>=0 &&a[i].compareTo(m)<=0)   // a[i]>=n && a[i]<=m 

瞭解完Biginteger的用法我們先測試一下

  • Biginteger的基本運算
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BigInteger a = scanner.nextBigInteger();
        BigInteger b = scanner.nextBigInteger();
        System.out.println(a+"+"+b+"="+a.add(b)); // 相加
        System.out.println(a+"-"+b+"="+a.subtract(b)); // 相減
        System.out.println(a+"*"+b+"="+a.multiply(b)); // 相乘
        System.out.println(a+"/"+b+"="+a.divide(b)); // 求商
        System.out.println(a+"%"+b+"="+a.remainder(b)); // 求餘
    }

結果:
在這裏插入圖片描述

熟悉完Biginteger的用法後我們回到正題求斐波那契數列的第100個數

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BigInteger a[] = new BigInteger[1000000];
        a[0] = BigInteger.valueOf(1);
        a[1] = BigInteger.valueOf(1);
        int n = scanner.nextInt();
        for (int i = 2; i < n; i++) {
            a[i] =a[i-1].add(a[i-2]);
        }
        System.out.println(a[n-1]);
    }

運行結果:
在這裏插入圖片描述

Biginteger不會有範圍的限制,但是運行速度會比較慢一些,當我們要計算相對比較大的數時在使用比較合適。

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