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.
def DivisibleSum(x):
sum = 0
for i in range(3, x):
if i % 3 == 0 or i % 5 == 0:
sum += i
else:
sum = sum
return sum
print(DivisibleSum(10))
print(DivisibleSum(1000))
23 233168
This is my original solution. First, start off with a container (empty), create a loop for every integers from 3 to the last number of the range. Within this loop, for each turn that encountering a divisible number for 3 or 5, then add the value to the container, otherwise leave it alone. Finally return the value at the end of the loop.
def DivisibleSum2(x):
sum = 0
for i in range(3,x):
if i % 3 == 0 or i % 5 == 0:
sum += i
# else then ignore
return sum
print(DivisibleSum2(10))
23
Then I found another solution which almost identical to my own answer, but without the else argument, probably making it even more concise. Base on what I can understand, when conditions for if statements were FALSE, then do nothing.
While this problem is just the entry point to the vast forrest of challenges lying ahead, I still quite gratified with my own solution being not so far off from the others. March on to the next one.