gpt4 book ai didi

python - 一点数学和逻辑

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:07 25 4
gpt4 key购买 nike

所以我这里有这个问题:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

我在这里写了这个:

def multiples(num, below):
counter = 1
z = 0
while True:
x = num * counter
if x < below:
z += x
else:
break
counter += 1
return z
below = 1000
print "Multiples of 3: " + str(multiples(3, below))
print "Multiples of 5: " + str(multiples(5, below))
print "Added: " + str(multiples(3, below) + multiples(5, below))

如果我将 below 设置为 10,我会得到正确答案 23

Multiples of 3: 18
Multiples of 5: 5
Added: 23

但是当我将它设置为 1000 时,我得到了这个:

Multiples of 3: 166833
Multiples of 5: 99500
Added: 266333

这应该是错误的,有什么我没有得到的吗?

最佳答案

实际上,一旦低于 1000,您就需要删除 15 的倍数,因为它会在 3 和 5 中重复。低于 10 时不会发生这种情况。

Multiple of 3 & 5  = (multiple of 3 + multiple of 5 - multiple of 15)

因此,您可以使用 Set 来存储这些倍数,以删除重复项..

关于python - 一点数学和逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12673041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com