猴子偷桃问题

来源:互联网 发布:淘宝如何申请延期收货 编辑:程序博客网 时间:2024/05/17 07:29

还是C语言版的问题,还是一个用递归的问题,很有意思。

五只猴子采得一堆桃子,猴子彼此约定隔天早起后分食。不过就在半夜里,一只猴子偷偷起来,把桃子平均分成五堆后,发现还多一个,它吃掉这个桃子,并拿走了其中的一堆。第二只猴子醒来,又把桃子平均分成五堆后,还多一个,它也吃掉这个桃子,并拿走了其中的一堆,第三只,第四只,第五只猴子都如此分食桃子,那么这堆桃子最少该有几个?

我的源码如下:

#include <stdio.h>

void Steal(int n, int *p);

main()
{
    int i = 1;    /* indicates the peach number */
    int counter;  /* stores the times of stealing */

    do
    {
        counter = 0;  /* reset the counter when loop starts */
        Steal(i++, &counter);
    } while (counter < 5);  /* end the loop when stealing time reaches 5 */

    printf("%d/n", i-1);
}

void Steal(int n, int *p)
{
    if (n % 5 == 1)
    {
        n -= n/5 + 1;
        ++*p;  /* increase the times of stealing */
        Steal(n, p);
    }
}