Project Euler Problem #1 Multiples of 3 or 5 states:
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 solved it using the following Python code:
#!/usr/bin/env python3
def sum_mult_3_5(max_num: int=1000) -> int:
"""
Euler Project
Problem 1
Multiples of 3 or 5
Find the sum of all the multiples of 3 or 5 below max_num.
Return the sum.
"""
total = 0
# First find the sum of all the multiples of 3.
# Also, store all the multiples of 3 in a dictionary.
multiples = {}
for mult in range(3, max_num, 3):
total += mult
multiples[mult] = 1
# Now add the sum of all the multiples of 5,
# using the dictionary to exclude common multiples.
for mult in range(5, max_num, 5):
if mult not in multiples:
total += mult
return total
if __name__ == "__main__":
print(f'Total = {sum_mult_3_5()}')
print(f'Total = {sum_mult_3_5(10)}')
Is this algorithm efficient?
- Is
rangea good choice? - Was it a good choice to first loop through the multiples of 3, then the multiples of 5?
- Was it a good choice to store the multiples of 3 in a dictionary?
I haven't looked at any other solutions or discussions for this problem yet, so as to not be biased.