Java算法中的兔子问题,假设有一只兔子,从出生后的第三个月起每个月都生一只兔子,小兔子长到第三个月后每个月又能生一只兔子,假设兔子都不死,问每个月的兔子总数是多少?
在写代码之前先想明白算法,假设第一个月的兔子数为:a,第二个月的兔子数为:b假设第一个月的新兔子数为 :new,老兔子数为:old 即:a=new + old;,则第二个月b= new + 2*old;到了第三个月的时候,则第二个月的new存储的已经是老兔子,新兔子实际是old产生的,所以第三个月的兔子数量为:c= 2*(new + old) + old,通过上面的规律我们发现:当月的new的数量和上个月的old数量是相等的,当月的old的数量是上个月的new与上个月的old的数量之和,当月的总数量是当月的new和当月的old的数量之和,因此转换为代码实现如函数:rabbitProblem_new(),程序清单如下:
package tuzi;
/**
*
* @author mjd
*/
public class Tuzi {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
rabbitProblem_new_digui(1,1,0);
}
p