题目2.一个农场有头母牛,现在母牛才一岁,要到四岁才能生小牛,四岁之后,每年生一头小牛。
假设每次生的都是母牛,并且也遵守4年才生育并生母牛的原则。且所生的牛都不会死
问20年之后共有多少头牛?用c语言解决
从现在开始,牛的数量组成数列a[n]:
1,1,1,2,3,4,5,7,10,14,19,26。。。(n=0,1,……20)
求a[20]
从a[4]开始有规律a[i]=a[i-1]+a[i-4]
则程序为
#include "stdio.h"
#include "conio.h"
void main()
{
int a[21];
a[0]=1;
printf("now:%d\n",a[0]);
a[1]=1;
printf("1 year after:%d\n",a[1]);
a[2]=1;
printf("2 years after:%d\n",a[2]);
a[3]=2;
printf("3 years after:%d\n",a[3]);
for(int i=4;i<=20;i++)
{
a[i]=a[i-1]+a[i-4];
printf("%d years after:%d\n",i,a[i]);
}
getch();
}
==============================================
结果
now:1
1 year after:1
2 years after:1
3 years after:2
4 years after:3
5 years after:4
6 years after:5
7 years after:7
8 years after:10
9 years after:14
10 years after:19
11 years after:26
12 years after:36
13 years after:50
14 years after:69
15 years after:95
16 years after:131
17 years after:181
18 years after:250
19 years after:345
20 years after:476
==============================================
import java.io.BufferedReader;
import java.io.InputStreamReader;
class ReadData
{
public static InputStreamReader inreader=new
InputStreamReader(System.in);
public static BufferedReader breader=new
BufferedReader(inreader);
public static int readInt()throws Exception
{
String str;
System.out.println("请输入年数:");
str=breader.readLine();
str=str.trim();
return
Integer.parseInt(str);
}
}
public class CountCow
{
public static void main(String[] args)throws
Exception
{
ReadData r = new
ReadData();
int n = r.readInt();
long i = CountCow.fib(n);
System.out.println(i);
}
public static long fib(int n)
{
long s = 1;
if(n==1||n==2||n==3)
{
s = 1;
}
else
{
s =
CountCow.fib(n-1) + CountCow.fib(n-3);
}
return s;
}
}