python - 一点数学和逻辑

标签 python math logic

所以我这里有这个问题:

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/

相关文章:

python - PySide 自定义选项卡

python - 在 Django 中全局设置 Decimal 选项

c++ - 没有得到数字基础检查器的正确解决方案

python - numexpr.evaluate ("a+b",out=a)

python - "InvalidArgumentError: Incompatible shapes: [64,40000] vs. [64] [Op:Mul]"在张量之间进行运算时?

math - 给定 f(x) 线性函数,如何获得二次贝塞尔控制点

javascript - 创建内容为 Latex、文本和图像的 PDF

c# - 从两个大整数中获取精确的百分比

iphone - Mobile Corona SDK 游戏 - 编程逻辑

c - 我的程序在关闭前不会运行我的 while 循环