菲波拉契数列(传统兔子问题)
生活随笔
收集整理的這篇文章主要介紹了
菲波拉契数列(传统兔子问题)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
題目:
古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數(shù)為多少???
?
斐波那契數(shù):
亦稱之為斐波那契數(shù)列(意大利語: Successione di Fibonacci),又稱黃金分割數(shù)列、費(fèi)波那西數(shù)列、費(fèi)波拿契數(shù)、費(fèi)氏數(shù)列,指的是這樣一個數(shù)列:0、1、1、2、3、5、8、13、21、……在數(shù)學(xué)上,斐波納契數(shù)列以如下被以遞歸的方法定義:F0=0,F1=1,Fn=Fn-1+Fn-2(n>=2,n∈N*),用文字來說,就是斐波那契數(shù)列列由 0 和 1 開始,之后的斐波那契數(shù)列系數(shù)就由之前的兩數(shù)相加。
斐波那契數(shù)列實(shí)現(xiàn)方式有多種,我這里舉例了三種實(shí)現(xiàn)。其中,遞歸算法最清晰,但是復(fù)雜度最高,不適合使用。
?
1 package programme; 2 /** 3 * 4 * 菲波拉契數(shù)列問題 語法定義:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*) 6 * 使用遞歸方法 耗時:25 7 */ 8 public class FibonacciRecursion { 9 public static void main(String[] args) { 10 // Scanner scanner=new Scanner(System.in); 11 // int index=scanner.nextInt(); 12 long time=System.currentTimeMillis(); 13 int index=32; 14 for (int i = 0; i <index; i++) { 15 System.out.println("第" + (i+1) + "個月的兔子對數(shù): " + getFibonacci(i)); 16 } 17 System.out.println("遞歸耗時:"+(System.currentTimeMillis()-time)); 18 } 19 20 //遞歸方法 21 public static int getFibonacci(int n){ 22 if(n==0||n==1) 23 return 1; 24 else 25 return getFibonacci(n-1)+getFibonacci(n-2); 26 } 27 28 } 1 package programme; 2 /** 3 * 菲波拉契數(shù)列問題 語法定義:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*) 6 * 使用傳統(tǒng)方式 耗時:1 7 */ 8 public class FibonacciTradition { 9 public static void main(String[] args) { 11 System.out.println("第1個月的兔子對數(shù):1"); 12 System.out.println("第2個月的兔子對數(shù):1"); 13 int i=32; 14 int s1=1,s2=1,count=0; 15 for (int j = 3; j<=i; j++) { 16 count=s1+s2; 17 s1=s2; 18 s2=count; 19 System.out.println("第"+j+"個月的兔子對數(shù):"+count); 20 } 22 } 23 } 1 package programme; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 7 /** 8 * 菲波拉契數(shù)列問題 語法定義:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*) 11 * 使用集合方式 耗時:3 12 */ 13 public class FibonacciCollection { 14 private List<Integer> list=new ArrayList<Integer>(); 15 16 public static void main(String[] args) { 18 FibonacciCollection demo=new FibonacciCollection(); 19 int index=24; 20 demo.put(index); 21 demo.get(index); 23 } 24 private void put(int n){ 25 list.add(1); 26 list.add(1); 27 for (int i = 3; i <= n; i++) { 28 list.add(list.get(i-2)+list.get(i-3)); 29 } 30 } 31 private void get(int n){ 32 int i=0; 33 for (int j:list) { 34 System.out.println("第" + ++i + "個月的兔子對數(shù): " + j); 35 } 36 } 37 38 39 40 }?
轉(zhuǎn)載于:https://www.cnblogs.com/snow1314/p/4978442.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的菲波拉契数列(传统兔子问题)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 龙族幻想哪个职业厉害 龙族小说在线全文阅
- 下一篇: 饿了么商家版如何部分退款给顾客