斐波那契数列:
package com.mj;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fib2(46));
}
//递归法 50之后卡住
public static int fib1(int n) {
if (n<=1) return n;
return fib1(n-1)+fib1(n-2);
}
//非递归
public static int fib2(int n) {
if (n<=1) return n;
int first = 0;
int second = 1;
for (int i = 0; i < n-1; i++) {
int sum = first + second;
first = second;
second = sum;
}
return second;
}
//优化
public static int fib3(int n) {
if (n<=1) return n;
int first = 0;
int second = 1;
while (n-- > 1) {
second += first;
first = second - first;
}
return second;
}
}