费波那契数列(意大利语:Successione di Fibonacci),又译为费波拿契数、斐波那契数列、费氏数列、黄金分割数列。
指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
实现:
/**递归实现
* @param n
* @return
*/
public static int fibonacci_recursion(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not less than zero");
return n <= 2 ? 1 : fibonacci_recursion(n-1) + fibonacci_recursion(n - 2);
}
递归一般随着n的增大效率很低
/**循环实现
* @param n
* @return
*/
public static int fibonacci_loop(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not less than zero");
if (n <= 2)
return 1;
int n1 = 1;
int n2 = 1;
int r = 0;
for (int i = 0; i < n - 2; i++) {
r = n1 + n2;
n1 = n2;
n2 = r;
}
return r;
}
使用int或者long来存储结果,一般随着n增大都会出现溢出的问题。
使用BigInteger
/**BigInteger循环实现
* @param n
* @return
*/
public static String fibonacii_bigInteger(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not less than zero");
if (n <= 2)
return "1";
BigInteger n1 = BigInteger.ONE;
BigInteger n2 = BigInteger.ONE;
BigInteger r = BigInteger.ZERO;
for (int i = 0; i < n - 2; i++) {
r = n1.add(n2);
n1 = n2;
n2 = r;
}
return r.toString();
}
BigInteger内部实现比较繁杂这也导致了速度稍稍慢了一些,但是不存在溢出的问题