Fortune left France title 5 basis class8- cow birth problems

Fortune left France title 5 basis class8- cow birth problems

1. Topic

Cow a cow born each year, the growth of the new-born cow after three years can be a raw cow per year, assuming that will not die. After seeking N, the number of cows.

2. Analysis

Listed first chart to find the law
Here Insert Picture Description
can be seen in the law: this year, equal to the sum of a cow cattle last year, plus all mature cattle have another (the number of mature cows), then how do you know the number of mature cattle it? According to the actual meaning of the questions is the sum of three years ago, cattle (cows three years ago, all fully mature can ensure fertility, and nearly two years of newborn cattle are immature)
the abstract is: F(N) = F(N - 1) + F(N - 3)namely 今年的牛 = 去年的牛 + 成熟的牛
① recursive: After obtaining the law, very easy to write a recursive code it! Note that only the first three years of the original cow can give birth, as a recursive stop conditions.
② non-recursive: Record number of cows for nearly three years, still with F(N) = F(N - 1) + F(N - 3)demand

3. recursive Code

int cow(int n)
{
	if(n <= 0)	return 0;
	if(n == 1 || n == 2 || n == 3)	return n;
	return cow(n - 1) + cow(n - 3);
}

4. nonrecursive

int cow1(int n)
{
	if(n <= 0)	return 0;
	if(n == 1 || n == 2 || n == 3)	return n;
	int prepre = 1;
	int pre = 2;
	int res = 3;
	int tmp1 = 0;
	int tmp2 = 0;
	for(int i = 4; i <= n;i++)
	{
		tmp1 = pre;
		tmp2 = res;
		res = prepre + res;

		prepre = tmp1;
		pre = tmp2;
	}
	return res;
}

The complete code

#include<iostream>
#include<string>
using namespace std;
//递归
int cow(int n)
{
	if(n <= 0)	return 0;
	if(n == 1 || n == 2 || n == 3)	return n;
	return cow(n - 1) + cow(n - 3);
}
//非递归
int cow1(int n)
{
	if(n <= 0)	return 0;
	if(n == 1 || n == 2 || n == 3)	return n;
	int prepre = 1;
	int pre = 2;
	int res = 3;
	int tmp1 = 0;
	int tmp2 = 0;
	for(int i = 4; i <= n;i++)
	{
		tmp1 = pre;
		tmp2 = res;
		res = prepre + res;

		prepre = tmp1;
		pre = tmp2;
	}
	return res;
}
int main()
{
	cout<< cow(15);
	cout<< cow1(15);
	return 0;
}
Published 51 original articles · won praise 1 · views 1361

Guess you like

Origin blog.csdn.net/shi_xiao_xuan/article/details/104827080