/* Classical question: Every month from 3 months to have a pair of rabbits, the rabbit long to the third month after the birth of a pair of rabbits, if the rabbit is not dead, ask each month the total number of rabbits. Analysis: First of all, we have to understand that the meaning of the title refers to the total number of rabbits per month, the hypothesis is that the rabbit is divided into small and junior high, rabbit from the birth of three months after the month will produce a pair of rabbits, then we assume the first month of the rabbit as a rabbit, the second month for the Rabbit, the third month
So the first month there were 1, 0, 0, the second month respectively is 0, 1, 0, the third month respectively 1, 0, 1, the fourth month respectively, 1, 1, 1, fifth month respectively 2, 1, 2, sixth month respectively 3, 2, 3, seventh months respectively 5, 3, 5 ...
The total number of rabbits were: 1, 1, 2, 3, 5, 8, 13 ... Then came a rule, from the third month onwards, the total number of rabbits is equal to the sum of the total number of rabbits in the previous two months, that is, the Fibonacci sequence. */classRabbitnumber {private VarRabbits: Long = 1private Varlastsecondrabbits: Long = 0private Varlastrabbits: Long = 0/** * Traverse the total number of rabbits from the first month to the nth month */ FunForeachmothstorabbits (moths:int) {println (System.currenttimemillis ()) for(Iinch1..moths) println ("section"+ i +"Rabbit count for months"+ getrabbits (i)) println (System.currenttimemillis ())}/** * Get the total number of rabbits in the current month */Private FunGetrabbits (moths:int): Long {if(moths = = 1 | | moths = = 2)returnRabbits= 1else if(moths = = 3)returnRabbits= 2Else{//Initialize the number of rabbits over the last one months and two monthsif(lastrabbits= = 0L &&lastsecondrabbits= = 0L) {lastsecondrabbits= Getrabbits (moths-2)lastrabbits= Getrabbits (moths-1)}//Calculate the number of rabbits returnedRabbits=lastrabbits+lastsecondrabbits /* Let the number of rabbits in two months equals the number of rabbits in the last one months, which makes the rabbit count this month for the next calculation (number of rabbits next month) more efficient and faster avoidance of redundant recursive effect calculation rate */lastsecondrabbits=lastrabbitslastrabbits=Rabbits returnRabbits }
}
}