java菲波那切数列通项,Java编程关于菲波那切数列的兔子繁殖问题

兔子繁殖问题:

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

1.问题分析:

adba0307f487115ed64fe825f2755029.png我们可以根据题目分析,得出如上图。兔子的对数从第一个月份开始分别是 1,1,2,3,5,8我们可以的得出这样关系

f(1) = 1

f(2) = 1

f(n) = f(n - 1) + f(n - 2)

1.采用第一种方法代码如下:

public class Rabbits {

public static void main(String[] args){

long a = System.currentTimeMillis();

for(int i = 1; i <= 40; i++) {

System.out.println(i + “:” + rabbits(i));

}

long b = System.currentTimeMillis();

long c = b-a;

System.out.println©;

}

public static long rabbits(int x) {

if(x == 1 || x == 2) {

return 1;

}else {

return rabbits(x - 1) + rabbits(x - 2);

}

}

}

0da84b8ad6825356128905bda7ee9e1f.png

编程中我们可以发现,递归虽然看起来程序清晰,当给更多的月份

或者给的数更大,速度就会很明显变慢,当为40的时候,耗费时间长达880毫秒。

2.采用第二种方法代码如下:

public class Rabbit {

static long now = 0l;

static long last2 = 1l;

static long last1 = 0l;

static long temp = 0l;

public static void main(String[] args) {

long a = System.currentTimeMillis();

for(int i = 1; i <= 40; i++) {

System.out.println( “第” + i + “月:” + rabbitnow(i));

}

long b = System.currentTimeMillis();

long c = b-a;

System.out.println©;

}

public static long rabbitnow(int x) {

now = last2 + last1;

temp = last1;

last1 = last2 + last1;

last2 = temp;

return now;

}

}

c0f81cad3fb45d842931cd028de32628.png

看起来逻辑较为复杂,但是耗费时间很少,只需5毫秒,在大量数据的情况下,最好使用第二种方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值