0

I am working on the Project Euler problems. I am on Problem 1 and for some reason I am getting the wrong answer for it. 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?

Thanks!

3 Answers 3

2

You're double counting numbers that are multiples of both 5 and 3, such as 15.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow I'm stupid. I didn't read the question carefully. It's multiples of 3 OR 5! Thanks so much
0

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.

I suggest using an if/else statement:

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; if it is not a multiple of 3, it checks whether it is a multiple of 5.

I also recommend using s as a variable name because it represents sum, which can't be used as it is a keyword. 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.

Good luck!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.