日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

斐波那契数列(fabnacci)java实现

發布時間:2025/4/5 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 斐波那契数列(fabnacci)java实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

斐波那契數列定義:From Wikipedia, the free encyclopedia

http://en.wikipedia.org/wiki/Fibonacci_number

In?mathematics, the?Fibonacci numbers?or?Fibonacci sequence?are the numbers in the following?integer sequence:[2][3]

or (often, in modern usage):

?(sequence?A000045?in?OEIS).

By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

In mathematical terms, the sequence?Fn?of Fibonacci numbers is defined by the?recurrence relation

with seed values[2][3]

or[4]

本例以后一種為例:

最簡單的一種:兩層遞歸

public static long fibonacci(int n){if(n==0) return 0;else if(n==1) return 1;else return fibonacci(n-1)+fibonacci(n-2);}

問題是:隨著n的數值逐漸增多,時間和空間耗費太大,讀者可以自行實驗。在我的機器上n=50時就不能忍受了。

考慮優化:一層遞歸

public static void main(String[] args) {long tmp=0;// TODO Auto-generated method stubint n=10;Long start=System.currentTimeMillis();for(int i=0;i<n;i++){System.out.print(fibonacci(i)+" ");}System.out.println("-------------------------");System.out.println("耗時:"+(System.currentTimeMillis()-start));} public static long fibonacci(int n) {long result = 0;if (n == 0) {result = 0;} else if (n == 1) {result = 1;tmp=result;} else {result = tmp+fibonacci(n - 2);tmp=result;}return result;}

遞歸時間減少了到不到50%

最好的方式,不使用遞歸的方式來做。

public static long fibonacci(int n){long before=0,behind=0;long result=0;for(int i=0;i<n;i++){if(i==0){result=0;before=0;behind=0;}else if(i==1){result=1;before=0;behind=result;}else{result=before+behind;before=behind;behind=result;}}return result;}

?

轉載于:https://www.cnblogs.com/davidwang456/p/4031167.html

總結

以上是生活随笔為你收集整理的斐波那契数列(fabnacci)java实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。