Classical question: There is a big rabbit, big Rabbit every month to give birth to a small rabbit, the second month the rabbit will grow into a big rabbit, if the rabbit is not dead, ask the number of the first n months of the rabbit total is how much?
Solution One, Cycle
1 Public LongSumRubbit1 (intN) {2 LongTotal = 0;//Total Rabbits3 intBig = 1;//total number of large rabbits4 intmiddle = 0;//total number of rabbits5 intLittle = 0;//number of small rabbits6 if(n==1){7Total =Big;8}Else if(n==2){9Little =Big;TenTotal = big+Little; One}Else{ ALittle =Big; - intBeformiddle = 0;//The total number of rabbits in the last month - for(inti=3;i<=n;i++){ theBeformiddle =Middle; -middle = little;//number of rabbits = number of small rabbits last month -little = big;//number of rabbits = number of big rabbits last month -Big = big +beformiddle;//Number of big rabbits = number of rabbits last month + number of rabbits in last month +Total = Big+middle+Little; - } + } A returnTotal ; at}
The method of solution is as follows:
Solution Two, recursion
1 Public LongSumRubbit2 (intN) {2 LongTotal = 0;//Total Rabbits3 if(n==1){4Total = 1;5}Else if(n==2){6Total = 2;7}Else if(n==3){8Total = 3;9}Else{TenTotal = SumRubbit2 (n-1) +sumrubbit2 (n-3); One } A returnTotal ; -}
Two ways to solve the solution are as follows:
Algorithm: Rabbit born Rabbit