我的推理哪里错了?

2024-04-23 18:03:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python编程的初学者,这是我在projecteuler(问题1)中的第一个程序。你知道吗

Euler项目中的问题1问:

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.

我觉得我的推理在某个地方是错的,但我看不出在哪里,为什么?我得到266333。你知道吗

i=0
s=0
j=0
r=0

while i<1000:
  s=s+i
  i=i+3

while j<1000:
  r=r+j
  j=j+5
print("sum=",s+r)    

Tags: orofthe项目程序编程allbelow
2条回答

你把一些数字加了两次。例如,15是3和5的倍数,但不能加两次。你知道吗

我会用模做一些简单的事情,而且只有一个循环。你知道吗

示例(尚未测试):

x=0
y=0

while x<1000
   if (x%5==0 or x%3==0):
      y=y+x
   x+=1

print("Sum equals ",y)  

问题是:

Find the sum of all multiples of 3 or 5 below 1000.

这里需要做的就是循环遍历1000下面的数字,如果数字可以被3i % 3 == 0)或5i % 5 == 0)整除,则将其附加到列表multiples并打印multiplessum(multiples))的所有元素的总和。你知道吗

multiples = []

for i in range(1000):
    if i % 3 == 0 or i % 5 == 0:
        multiples.append(i)

print sum(multiples)
# 233168

更简化的代码:

print sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
# 233168

相关问题 更多 >