0
Python: I was practicing writing code to answer a problem on ProjectEuler, but it keeps giving me wrong answer.
The question was: 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. The code I wrote: i = 1 ans1 = 0 num1 = 0 while ans1 <= 1000: ans1 = i * 3 if ans1 <= 999: print(ans1) num1 = num1 + ans1 i += 1 i = 1 ans2 = 0 num2 = 0 while ans2 <= 1000: ans2 = i * 5 if ans2 <= 1000: print(ans2) num2 = num2 + ans2 i += 1 else: print(""" Answer is: """) print(num1+num2) The answer the code above is giving me is 269340, but the site says that that's the wrong answer. Please help.
2 ответов
+ 2
Check this:
i = 1
ans1 = 0
num1 = 0
while ans1 <= 1000:
ans1 = i * 3
if ans1 <= 999:
print(ans1)
num1 = num1 + ans1
i += 1
i = 1
ans2 = 0
num2 = 0
while ans2 <= 1000:
ans2 = i * 5
if ans2 <= 1000:
print(ans2)
num2 = num2 + ans2
i += 1
else:
print("""
Answer is: """)
print(num1+num2)
I check it with smallest numbers (not below 1000 but 10 => easier find mistake) and work fine.
You miss one space before 'num1 = num1 + ans1' and 'num2 = num2 + ans2' and interpreter sum numbers with every while loop without if condiction. I hope I helped
0
Thanks Marek Kazimierczak for the response, but that wasn't it.
After trial and error I realized that some of the multiples of 3 are also multiples of 5. So it was adding those specific numbers twice. So, I created a third while loop to add up all the multiples of 15 and subtract that from the total.
Final code was:
i = 1
ans1 = 0
num1 = 0
while ans1 <= 1000:
ans1 = i * 3
if ans1 <= 1000:
print(ans1)
num1 = num1 + ans1
i += 1
i = 1
ans2 = 0
num2 = 0
while ans2 <= 995:
ans2 = i * 5
if ans2 <= 995:
print(ans2)
num2 = num2 + ans2
i += 1
i = 1
ans3 = 0
num3 = 0
while ans3 <= 1000:
ans3 = i * 15
if ans3 <= 1000:
print(ans3)
num3 = num3 + ans3
i += 1
else:
print("""
Answer is: """)
print(num1+num2-num3)
But thanks for pointing out the missing space, I am practicing on notepad and it gets a bit confusing.