一头小母牛,以出生起第四个年头开始每年生一头母牛,第N年有多少头母牛?
我想了好久一只想不出来合适的算法……,请大家帮帮我
[此贴子已经被kai于2004-07-30 23:50:37编辑过]
母牛问题啊,给你个C的
#include <stdio.h> void fcow(int n,int *s,int k) { int i,bc=0,sc0=0,sc1=1,sc2=0; /*bc是大母牛,sc0是刚出生的小母牛,sc1是1岁小母牛,sc2是2岁*/ for(i=1;i<n;i++) { sc0=bc; bc+=sc2; sc2=sc1; sc1=sc0; } s[k]=bc+sc2+sc1; } void main () { int n,i,s[50],k=0; while(scanf("%d",&n)!=EOF) fcow(n,s,k++); for(i=0;i<k;i++) printf("%d\n",s[i]); }
// My C++ solution
#include <iostream> using namespace std;
class cow { private: int birthyear; int age; bool geboren; public: cow(){ birthyear = 0; age = 0; geboren = false;} cow(int year, int theage = 1) { birthyear = year; age = theage; geboren = true; } void growup(int year) //year : the actual year { age = year - birthyear + 1; } bool bearing() { if(age>=4) return true; else return false; } bool isgeboren(){return geboren;} };
class cattle_farm { private: int cow_num; enum{ MAX = 50000}; enum{ begin = 1}; int end; cow thecows[MAX]; public: cattle_farm(){ cow_num = 1; thecows[0] = cow(begin);} void propagate() { cout<<"Please set N for the years\n"; cout<<"N = "; cin>>end; for(int i = begin; i<=end; i++) { int j = 0; do { thecows[j].growup(i); if(thecows[j].bearing()) { cow_num++; thecows[cow_num-1] = cow(i); } j++; }while(thecows[j].isgeboren()); } } void show_cow_nuw() { cout<<"after "<<end<<" years there are "<<cow_num<<" in this cattle farm.\n"; } };
int main() { cattle_farm mycattle_farm; mycattle_farm.propagate(); mycattle_farm.show_cow_nuw(); return 0; }
应该就是a[n]={n,n-3,n-2,...........2,1},然后 求和:3+1+2+3+4+.....+n-5;
#include <iostream> using namespace std; int main() { int n,sum=0; cin>>n; int array[n]; array[0]=n; for(int i=1;i<n-2;i++) { array[i]=n-i-2;} int i; for (i=0;i<n-2;i++) {cout<<array[i]<<" "; } if (n>=5){ for(i=1;i<n-4;i++) { sum+=i; } sum+=3;} else if(n==4) sum=2; else sum=1; cout<<"\n"<<sum; system("pause"); return 0; }