简体   繁体   English

蛮力解决方案返回了 Project Euler 问题 31 的错误答案

[英]Brute force solution returns wrong answer for Project Euler problem 31

I'm having trouble with Project Euler problem 31 .我遇到了Project Euler 问题 31 的问题 The correct answer is 73,682, and my answer is 73,681.正确答案是 73,682,我的答案是 73,681。 Here is the problem:这是问题所在:

In the United Kingdom the currency is made up of pound (£) and pence (p).在英国,货币由英镑 (£) 和便士 (p) 组成。 There are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).一般流通的硬币有八种:1便士、2便士、5便士、10便士、20便士、50便士、1英镑(100便士)和2英镑(200便士)。

It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p.可以通过以下方式赚取 £2:1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p。

How many different ways can £2 be made using any number of coins?使用任意数量的硬币可以有多少种不同的方法来制作 2 英镑?

And my code:还有我的代码:

counter = 0
for a in range(3):
    for b in range(5):
        if 100 * a + 50 * b > 200:
            break
        for c in range(11):
            if 100 * a + 50 * b + 20 * c > 200:
                break
            for d in range(21):
                if 100 * a + 50 * b + 20 * c + 10 * d > 200:
                    break
                for e in range(41):
                    if 100 * a + 50 * b + 20 * c + 10 * d  + 5 * e > 200:
                        break
                    for f in range(101):
                        if 100 * a + 50 * b + 20 * c + 10 * d + 5 * e + 2 * f <= 200:
                            counter += 1
print(counter)

The problem is that your code doesn't consider the case where you just have a £2 coin.问题是您的代码没有考虑您只有 2 英镑硬币的情况。 You can just initialize the variable counter to 1 to fix this issue.您只需将变量counter初始化为 1 即可解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM