Algorithm: Rabbit born Rabbit

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.