若有一只免子每个月生一只小免子,一个月后小免子也开始生产。起初只有一只免子,一个月后就有两只免子,二个月后有三只免子,三个月后有五只免子(小免子投入生产)....
{
public static void main(String[] args)
{
// args[0]参数 表示第几个月
System.out.println(new Fibonacci().calRabbit(Integer.parseInt(args[0])));
}
private int calRabbit(int n)
{
if ((n ==1) || (n == 2))
{
return 1;
}
else
{
return calRabbit(n-2) + calRabbit(n-1);
}
}
}
打印出每个月的兔子的总数,例如1、1 、2、3、5、8、......
public class Fibonacci { public static void main(String[] args) { int[] fib = new int[20]; fib[0] = 0; fib[1] = 1; for(int i = 2; i < fib.length; i++) fib[i] = fib[i-1] + fib[i-2]; for(int i = 0; i < fib.length; i++) System.out.print(fib[i] + " "); System.out.println(); } }这就是斐波那契数列,是该数学家在举例时引用的兔子繁殖说明,可以用递归编程,也就是第三项为前两项之和。
public class Fibonacci { public static void main(String[] args) { int x=1,y=1; System.out.println(x+" "); for(int i=1;i<=20;i++) { System.out.println(y+" "); y=x+y;x=y-x; } } }public class Fibonacci
{
public static void main(String[] args)
{
// args[0]参数 表示第几个月
System.out.println(new Fibonacci().calRabbit(Integer.parseInt(args[0])));
}
private int calRabbit(int n)
{
if ((n ==1) || (n == 2))
{
return 1;
}
else
{
return calRabbit(n-2) + calRabbit(n-1);
}
}
}
递归是不错,但递归冗余造成冗余运算,当到第40个月时,f40=202334155,总的递归调用次数大于300000000,递归的调用会成爆炸性增长
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Rabbit> Rabbitlist = new ArrayList<Rabbit>(); Rabbitlist.add(new Rabbit()); for (int i = 0; i < 40; i++) { System.out.print(Rabbitlist.size()); System.out.print(","); for (Rabbit rabbit : (ArrayList<Rabbit>) Rabbitlist.clone()) { if (rabbit.isSmall()) { rabbit.Growing(); } else { Rabbitlist.add(rabbit.Create()); } } } } } class Rabbit { boolean small; Rabbit() { small = true; } public Rabbit Growing() { small = false; return null; } public Rabbit Create() { return new Rabbit(); } public boolean isSmall() { return small; } }