简体   繁体   English

欧拉 Python 项目

[英]Project Euler Python

I am working on the Project Euler problems.我正在研究 Project Euler 问题。 I am on Problem 1 and for some reason I am getting the wrong answer for it.我在问题 1 上,出于某种原因,我得到了错误的答案。 I don't know if its my math logic that's the problem or if the logic for the code is wrong.我不知道是我的数学逻辑有问题,还是代码的逻辑错误。 Here's the code:这是代码:

def getSumMult3_5(n):
    count = 0
    i = 0
    i_1 = 0
    while i*5 < n:
        count += i*5
        i += 1
    while i_1*3 < n:
        count += i_1*3
        i_1 += 1
    return count

print getSumMult3_5(1000)

It's returning that它回来了

count = 266333

but that is not the correct answer.但这不是正确答案。 Count should equal 233168. Can anybody help me figure out why it's doing this? Count 应该等于 233168。谁能帮我弄清楚为什么要这样做?

Thanks!谢谢!

您正在重复计算 5 和 3 倍数的数字,例如 15。

You are double counting multiples of 15. You can solve this by introducing a third while statement to decrease the count by 1 for each multiple of 15.您正在重复计算 15 的倍数。您可以通过引入第三个 while 语句来解决这个问题,为每个 15 的倍数将计数减 1。

I suggest using an if/else statement:我建议使用 if/else 语句:

def getSumMult3_5(n):
  s = 0
  for i in range(1, n+1):
    if i%3==0:
      s+=i
    elif i%5==0:
      s+=i
  return s

print getSumMult3_5(1000)

This is because that if the number is a multiple of 3, it does not check whether it is a multiple of 5;这是因为如果这个数是3的倍数,它不检查它是否是5的倍数; if it is not a multiple of 3, it checks whether it is a multiple of 5.如果不是3 的倍数,则检查它是否是 5 的倍数。

I also recommend using s as a variable name because it represents sum, which can't be used as it is a keyword.我还建议使用s作为变量名,因为它代表 sum,不能使用,因为它是关键字。 Count seems to refer to the number of times something occurs.计数似乎是指某事发生的次数。

By only using one variable, and using an if/else statement, execution time will be less and it will be less confusing to read.通过只使用一个变量,并使用 if/else 语句,执行时间会更少,阅读也不会那么混乱。

Good luck!祝你好运!

Here's my code:这是我的代码:

running_sum = 0





for i in range(1,1000):
    if i % 3 == 0:
      running_sum+=(i) 
      
    elif i % 5 == 0:
      running_sum+=(i)
print running_sum
  

You're double-counting numbers like 15 that are multiples of both你在重复计算像 15 这样是两者倍数的数字

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

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