I am relatively new to coding in general and started Project Euler to bring my coding a bit further. Spent some time thinking of how to work the first question on my own and tried using recursive functions, unfortunately always getting the same mistake (266333). What did i miss? Any big mistake to learn from?
The original question reads: "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 function(i, j, h, k):
if j < 1000 and k < 1000:
i = i + j
h = h + k
return function(i, j+3, h, k+5)
elif j < 1000 and k >= 1000:
i = i + j
return function(i, j+3, h, k)
elif j >= 1000 and k < 1000:
h = h + k
return function(i, j, h, k+5)
else:
print (i + h)
function(0,0,0,0)
Where i is the sum of multiples of 3, h is the sum of multiples of 5, j is multiples of 3 and k is multiples of 5.
I'd strongly advise against recursion, since it might work for small number but not for bigger ones, and even if the solution might work, it would teach you a wrong approach.
This is more pythonic, reusable, faster and simpler to read and correct.
Your mistake is that you are including numbers divisible by 15 twice: Once as a multiple of 3, and once as a multiple of 5.
For what it's worth, here's a concise way of computing this sum: