Java还要再学一遍基础(十四)实现斐波那契数列

费波那契数列意大利语: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内部实现比较繁杂这也导致了速度稍稍慢了一些,但是不存在溢出的问题



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值