JAVA 递归与非递归斐波那契数列的实现

124 篇文章 1 订阅
7 篇文章 0 订阅


今天练习时碰到斐波那契数列,循环和递归的代码分别统计了一下执行时间。递归还是相当慢的。

找了一篇介绍比较详细的博文,闲暇时可以再看看。 链接





package exrcise;

public class Demo1 {

	public static void main(String[] args) {
		/*
		 *	用循环实现不死神兔
			故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契。
			在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,
			再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,一年内没有发生死亡,
			问:一对刚出生的兔子,一年内繁殖成多少对兔子?
			
			 1 1 2 3 5 8 13 21 
		 * */
		long start = System.currentTimeMillis();
		int month = 44;
		fibonacci(month);
		long end = System.currentTimeMillis();
		System.out.println("--------------------------------------------");
		long used = end - start;
		System.out.println("当前程序耗时:" + used + "ms.");
		
		System.out.println("--------------------------------------------");
		long start1 = System.currentTimeMillis();
		System.out.println(cFibonacci(44));
		long end1 = System.currentTimeMillis();
		long used1 = end1 - start1;
		System.out.println("当前程序耗时:" + used1 + "ms.");
	}

		
	private static long cFibonacci(int month) {

		if(month == 1 || month == 2) {
			return 1;
		}else {
			return cFibonacci(month-1) + cFibonacci(month - 2);
		}

	}


	private static void fibonacci(int month) {
		long nextMonth = 1;
		long thisMonth = 1;
		long temp = 0;
		for(int i=1; i<=month; i++) {
			if(i <= 2) {
				nextMonth = 1;
			}else {
				temp = nextMonth;
				nextMonth = nextMonth + thisMonth;
				thisMonth = temp;
			}	
			System.out.println(nextMonth);
		}
		
	}

}
1
1
2
...
701408733
--------------------------------------------
当前程序耗时:4ms.
--------------------------------------------
701408733
当前程序耗时:2793ms.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值