PackageJavablog;
/* Classical problems: 3 months from the month of a pair of rabbits, the rabbit long to the third month after the birth of a pair of rabbits each month, if the rabbit is not dead, ask the total number of rabbits each month. Analysis: First we have to understand the meaning of the topic refers to the total logarithm of the rabbit every month; if the rabbit divided into small and middle three species, rabbit from the birth of three months after each month will produce a pair of rabbits, then we assume the first month rabbit for the Rabbit, the second month for the Rabbit, the third month after the Big Rabbit,
Then the first month were 1, 0, 0, the second month were 0, 1, 0, the third month were 1, 0, 1, fourth month respectively, 1, 1, 1, fifth month respectively 2, 1, 2, sixth month respectively 3, 2, 3, seventh month respectively 5, 3, 5 ...
The total number of rabbits were: 1, 1, 2, 3, 5, 8, 13 ... So we have a rule that from the third month onwards, the total number of rabbits behind is equal to the total number of rabbits in the preceding two months, which is the Fibonacci sequence. */Public classRabbitnumber {Private LongRabbits= 1;Private Longlastsecondrabbits,lastrabbits; /** * Iterate the total number of rabbits from the first month to the nth month * * *Public voidForeachmothstorabbits (intMoths) {System. out. println (System.currenttimemillis ()); for(inti = 1;i<= moths;i++) System. out. println ("First"+i+"The number of rabbits a month"+getrabbits (i)); System. out. println (System.currenttimemillis ()); /** * Get the total number of rabbits for the current month * * * *Private LongGetrabbits (intMoths) {if(moths = 1 | | moths==2) returnRabbits= 1;else if(moths = 3) returnRabbits= 2;Else{//Initialize the number of rabbits for one months and two monthsif(lastrabbits= = 0 &&lastsecondrabbits==0) {lastsecondrabbits= Getrabbits (moths-2);lastrabbits= Getrabbits (moths-1); }//Calculate the number of rabbits returnedRabbits=lastrabbits+lastsecondrabbits; * Let the number of rabbits two months equals the number of rabbits in one months, so that last month is equal to the number of rabbits this month for the next calculation (Rabbit number next month) more efficient and quick to avoid redundant recursive effect of the calculation rate * *lastsecondrabbits=lastrabbits;lastrabbits=Rabbits; returnRabbits; }
}
}