今年母牛的头数来源于两个方面,一个是原有母牛头数即去年母牛头数,二是母牛生出的小牛即3年前的母牛的头数;
所以得出递推公式:f(n)=f(n-1)+f(n-3)n>=4;
类似于斐波纳契数列;
代码的实现还是自己写写比较好,这样才能提高,希望对你有帮助,
递推公式易得啊a[n]=a[n-1]+a[n-3];前四组数据单独赋值。
我空间有代码
有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
定义几个变量 sum = 1;//最开始最老的母牛1头
num = 1;//每年增加的数量,从第一年开始增加1
后续n年增加的头数关系.
每四年一轮回就增加前一年num+1个数.
num1 = 1; sum = 2
num2 = 1; sum = 3
num3 = 1; sum = 4 //前三年num = 1;
num4 = 2; sum = 6 //第四年num++;num = 2依次类推如下:
num5 = 3; sum = 9
num6 = 4; sum = 13
num7 = 5; sum = 18
num8 = 6; sum = 24
主要循环表达
for(i=1;i<=n;i++)
{
sum+=num;
if(i%4==0)
num++;
}
希望对你有帮助
// female cow.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "assert.h"
using namespace std;
long g_nMaxSmallFemale=10000;
#define g_nSize 2
//counting start from year 1
void DeleteItem(int *p,const int &nIndex,int &n,int &nCallStartFlag)
{
nCallStartFlag=0;
if(nIndex>-1)
{
int nTemp=n-1;
int nValidDataIndex=nIndex+1;
for(int i=nIndex;i
while(1)
{
if(p[nValidDataIndex]!=0)
{
p[i]=p[nValidDataIndex];
nValidDataIndex++;
break;
}
else
{
nValidDataIndex++;
nTemp--;
}
}
}
n=nTemp;
}
nCallStartFlag=1;
}
int SumofCow(const int &n)
{
if(n>=0)
{
int nBigFemale=1;
int nSum=0;
int nSmallFemale=0;
int *pSmallFemale;
pSmallFemale=(int*)malloc(g_nMaxSmallFemale*sizeof(int));
assert(pSmallFemale!=NULL);
memset(pSmallFemale,-1,g_nMaxSmallFemale);
//cout<
for(int i=1;i
int nCountofGrowUp=0;
int nFirstZeroValue=-1;
//update smallfemale data and array related
for(int i1=0;i1
if(pSmallFemale[i1]>0)--pSmallFemale[i1];
if(pSmallFemale[i1]==0)
{
nCountofGrowUp+=1;if(nFirstZeroValue==-1)nFirstZeroValue=i1;
}
}
//调用延时
int nStartOrNot=1;
DeleteItem(pSmallFemale,nFirstZeroValue,nSmallFemale,nStartOrNot);
while(nStartOrNot==0);
//add new smallfemale to array
int nAddIndex=nSmallFemale;
nBigFemale+=nCountofGrowUp;
while(1)
{
if( nAddIndex==g_nMaxSmallFemale|| nAddIndex+nBigFemale>=g_nMaxSmallFemale)
{
//free(pSmallFemale);pSmallFemale=NULL;
g_nMaxSmallFemale*=g_nSize;
pSmallFemale=(int*)realloc(pSmallFemale,g_nMaxSmallFemale*sizeof(int));
assert(pSmallFemale!=NULL);
//memset(pSmallFemale,-1,g_nMaxSmallFemale);
}
else break;
}
int k;
for(k=nSmallFemale;k
pSmallFemale[k]=4;
}
nSmallFemale=k;
nSum=nSmallFemale+nBigFemale;
}
nSum=nSmallFemale+nBigFemale;
free(pSmallFemale);pSmallFemale=NULL;
return nSum;
}
return 0;
}
int main(int argc, char* argv[])
{
int n;
while(cin>>n,n>=0)
cout<
return 0;
}
60年内可算 过大内存罩不住 你可以优化下内存分配 找简便的算法才能算更多位 规律比较明显(后面才看到 哈哈)