The story of a cow

Source: Internet
Author: User

There is a cow, which has a small cow at the beginning of each year.
Each heifer starts its fourth year with a heifer.
Please program implementation how many cows are there in the first n years?

/*
There is a cow, which has a small cow at the beginning of each year.
Each heifer starts its fourth year with a heifer.
Please program implementation how many cows are there in the first n years?

Title Requirements:
Input
The input data consists of multiple test instances, one for each test instance, including an integer n (0< n<), and the meaning of n as described in the topic.
N=0 indicates the end of the input data and does not handle it.
Output
For each test instance, output the number of cows in the nth year.
Each output occupies one row.
Sample Input
2
4
5
0
Sample Output
2
4

Analysis: This question is similar to another interesting classical math problem: there is a pair of rabbits, from the 3rd month after birth, every month has a pair of rabbits.
The rabbit grew to the 3rd month, and every month he gave birth to a pair of little rabbits. Suppose all the rabbits do not die, ask the total number of rabbits each month?
This is a typical Fibonacci sequence problem:
F1=1 (N=1)
F2=1 (n=2)
F3=F1+F2 (n>=3)

The number of cows is also a regular form of the sequence, so we must find a recursive formula, after analysis
F1=1 (N=1)
f2=2 (n=2)
F3=3 (n>=3)
F4=F1+F3 (n>=4)

*/

#include <iostream>using namespacestd;intMain () {intn,i,f1=1, f2=2, f3=3;//F1,F2,F3 represents the number of cows for three consecutive years, and N represents the first few yearsCin>>N; while(n!=0) {  if(n==1|| n==2|| n==3)//If the year entered is 1th, 2, 3 years{cout<<n<<Endl; CIN>>N; Continue; } F1=1; F2=2; F3=3;  for(i=1; i<= (n4)/3+1; i++)//recursive from the 4th year onwards{F1=f1+f3; F2=f1+F2; F3=f2+f3; }  if(n%3==1) cout<<f1<<Endl; if(n%3==2) cout<<f2<<Endl; if(n%3==0) cout<<f3<<Endl; CIN>>N;} return 0;} 

The story of a cow

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.