Reputation: 101
I'm an absolute beginner in programming in Python and this is my first program in Project Euler (problem 1).
Problem 1 in Project Euler asks:
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.
I feel like my reasoning is wrong somewhere, but I can't see where or why? I get 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)
Upvotes: 0
Views: 83
Reputation: 22998
The question is:
Find the sum of all multiples of
3
or5
below1000
.
All you need to do here is loop through the numbers below 1000
, if the number is divisible by 3
(i % 3 == 0
) or 5
(i % 5 == 0
), append it to a list multiples
and print the sum of all the elements of multiples
(sum(multiples)
).
multiples = []
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
multiples.append(i)
print sum(multiples)
# 233168
More simplified code:
print sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
# 233168
Upvotes: 2
Reputation: 1587
You're adding some numbers twice. 15, for example, is a multiple of 3 and 5, but you shouldn't add it twice.
I'd do something simpler using modulo, and only one loop.
Example (haven't tested):
x=0
y=0
while x<1000
if (x%5==0 or x%3==0):
y=y+x
x+=1
print("Sum equals ",y)
Upvotes: 0