Fibonacci数列Java实现

Fibonacci数列:如是:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

f(0) = 1; f(1) = 1; f(n) = f(n-1)+f(n-2) n>1;

 1 import java.util.Arrays;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         Test test = new Test();
 7         int n = 15;
 8         int[] fibonacciArray = new int[n]; 
 9         for (int i = 0; i < n; i++) {
10             fibonacciArray[i] = test.fibonacci(i);//将n处的值存入数组中
11         }
12         System.out.println(Arrays.toString(fibonacciArray));
13     }
14     
15     //递归求解n处的值
16     private int fibonacci(int n){
17         if(n==0||n==1){
18             return 1;
19         }
20         else if(n>1){
21             return fibonacci(n-1)+fibonacci(n-2);
22         }
23         else{
24             return 0;
25         }
26     }
27 }

输出:
   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
 1 //普通循环求解
 2 int n1 = 15;
 3 for(int i = 0; i<n1; i++){
 4     if(i==0 || i==1){
 5     fibnacciArray1[i] = 1;
 6     }
 7     else{
 8         fibnacciArray1[i] = fibnacciArray1[i-1]+fibnacciArray1[i-2];
 9     }
10 }
11 System.out.println(Arrays.toString(fibnacciArray1));

输出:
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

 

转载于:https://www.cnblogs.com/stivebone/p/5671684.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值