猴子分桃问题,c语言,急~~~
发布网友
发布时间:2022-05-16 20:44
我来回答
共2个回答
热心网友
时间:2024-03-01 22:39
答案是:至少剩8188,原来至少84371
/*猴子分桃改版*/
#include <stdio.h>
int main()
{
int previous (int current, int share, int remaining);/*定义分桃函数,current分完剩下数值,share份数,remaining被吃的余数,返回值为分前数目*/
int monkeyNum1=3, monkeyNum2=5;/*两组猴子数*/
int peachNum, peachNumr;/*桃子的总数和最后剩下的数目*/
int i,j;/*中间变量*/
for (i=1;i<10000;i++)
{
peachNum=i;
for(j=1;j<=monkeyNum2;j++)
{
peachNum=previous(peachNum, monkeyNum2, 1);
if(peachNum==0)
break;
}
if(peachNum==0)
continue;
for(j=1;j<=monkeyNum1;j++)
{
peachNum=previous(peachNum, monkeyNum1, 2);
if(peachNum==0)
break;
}
if(peachNum==0)
continue;
else
break;
}
peachNumr=i;
printf("At last remaining: %d\nNumber of all the peaches: %d\n",peachNumr,peachNum);
return 0;
}
int previous (int current, int share, int remaining)
{
int previousNum;
previousNum=current*share/(share-1)+remaining;
if(previousNum%share!=remaining)
return 0;
return previousNum;
}
热心网友
时间:2024-03-01 22:40
用递归