错误的结果是项目euler 31

时间:2012-02-06 15:25:22

标签: c++ c

我试图解决project euler 31

  

在英格兰,货币由英镑,英镑和便士,p和   一般流通中有八个硬币:

     

1p,2p,5p,10p,20p,50p,£1(100p)和£2(200p)。有可能   以下列方式赚取2英镑:

     

1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p

     

2英镑有多少种不同的方式   用任意数量的硬币制作?

使用此代码:

#define to2(x) ((x)/2+1)

int to5(x)
{
    int acc=1;
    for(;x>0;x-=5)
        acc+=to2(x);
    return acc;
}

int to10(x)
{
    int acc=1;
    for(;x>0;x-=10)
        acc+=to5(x);
    return acc;
}

int to20(x)
{
    int acc=1;
    for(;x>0;x-=20)
        acc+=to10(x);
    return acc;
}

int to50(x)
{
    int acc=1;
    for(;x>0;x-=50)
        acc+=to20(x);
    return acc;
}

int to100(x)
{
    int acc=1;
    for(;x>0;x-=100)
        acc+=to50(x);
    return acc;
}

int main()
{
    int test = to100(200)+1;
    printf("%d",test);
    return 0;
}

但是代码给了73685,而不是73682,但我不知道为什么,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:6)

为什么要将acc初始化为1? (当x是函数数量的倍数时,这是有意义的,但只有那时。)将其更改为0,并将循环条件更改为x>=0。 (如果我理解你的代码)。

答案 1 :(得分:1)

这个问题不需要C代码来解决,这是设置选择的问题。您需要解决number of ways to select n coins where n > 0 and sum = 2£,您应该查找Set theory 这应该可以帮助您找到一个线性方程来计算数字。