/*問題描述*//**五只猴子一起摘了一堆桃子,因為太累,決定先睡一覺再分。 *過了不知多久,來了一只猴子,它見別的猴子沒來,便將一堆桃子平均分成 5 份,結果*多了一個,就將多的這個吃了,拿走其中的一堆。 *又過了不知多久,第二只猴子來了,它不知道有一個同伴已經來過,還以為自己是第一*個,便將地上的桃子平均分成 5 份,發現也多了一個,同樣吃了這一個,拿走其中的一*堆。第3只,第4只,第5 只猴子都是這樣...... *問這5只猴子至少摘了多少個桃子? *//*程序說明:(1)修改宏 MAXNUM 的大小,重新編譯后即可搜索出所有0~MAXNUM 之間滿足條件的數字。(2)這是一種比較直接的算法,有許多地方值得改進。歡迎大家一起探討(3)本程序用vc++6.0在win2000環境中編譯通過。*//*zhaitao.c*/#include "stdio.h" #include "stdlib.h" #include "math.h" #include "string.h"#define bool int #define true 1 #define false 0#define MAXNUM 5000/*target number strUCt*/ typedef struct tagTARGETNUM { int totalN; int remains; } _TargetNum, *p_TargetNum; typedef struct tagTAGTEST { _TargetNum targetNum[MAXNUM]; int count; /*num satisfied our condition*/ }_tagTest, p_tagTest;bool monkey(int iOriginal, int * PRemains); bool SepPeach(int iTotal, int *remains); void FindSmallest(_tagTest* tgtst);void main(void) { int i = 0; int tempRmn = 0; bool ret = false; _tagTest tgtst; memset(&tgtst,0,sizeof(_tagTest));
printf("test-- from:%d , to:%dpress any key to continue",i,MAXNUM); getchar(); printf("starting find..."); for(; i < MAXNUM; i++) { if( (ret = SepPeach(i,&tempRmn)) != true)
else { tgtst.targetNum[tgtst.count].totalN = i; tgtst.targetNum[tgtst.count++].remains = tempRmn; } } FindSmallest(&tgtst); getchar(); }/************************************************************************/ /* if the original number satified our condition, the function will return true, else return false. */ /************************************************************************/ bool monkey(int iOriginal, int * pRemains) { // int remains = 0;
return true; }bool SepPeach(int iTotal, int* remains) { int flag = false; int tempNum = 0; //temporary number of remained peaches int i = 0; tempNum = iTotal; for(i = 0; i < 5; i++) { if((flag = monkey(tempNum, &tempNum)) == false) { printf("total num of peaches %d does not satisfy our condition!",iTotal); return false; } }
*remains = tempNum; printf("total num of peaches: %d, remains: %d ", iTotal, *remains); return true; }void FindSmallest(_tagTest* tgtst) { int i; //int temp = -1; _TargetNum tempTn; tempTn.totalN = 1000000; printf("we found %d nums which satisfied our condition ",tgtst->count); if (tgtst->count == 0) else { printf("----these nums are:"); } for(i = 0; i < tgtst->count; i++) { printf("total:%d remains:%d",tgtst->targetNum[i].totalN,tgtst->targetNum[i].remains); if(tempTn.totalN >= tgtst->targetNum[i].totalN) { tempTn.totalN = tgtst->targetNum[i].totalN; tempTn.remains = tgtst->targetNum[i].remains;
} } printf("----------------------------------------"); printf("the smallest total num of peaches is: %d, the remains is: %d",tempTn.totalN,tempTn.remains); return; }