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.
# Classic off-by-one error.
# https://en.wikipedia.org/wiki/Off-by-one_error
total = 0
euler = 0
while euler < 999:
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
euler = euler + 1
print(total)
232169
# Fix off-by-one error by changing comparison operator
total = 0
euler = 0
while euler <= 999:
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
euler = euler + 1
print(total)
233168
# Replace magic number with a variable (n).
# Also, let the machine do the dirty work.
# That's why n is 1000 and the comparision is with n - 1.
# Having the computer calculate n - 1 is the dirty work.
n = 1000
total = 0
euler = 0
while euler <= n - 1:
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
euler = euler + 1
print(total)
233168
# Use n instead of n-1 for standard programming conventions.
# For loops that execute n times and start at 0
# the convention is to initialize the loop counter with 0
# for the comparision to be loop counter less than n.
#
# The C version of the idiom is
#
# for (euler = 0; euler < n; euler++)
# ; /* whatever */
n = 1000
total = 0
euler = 0
while euler < n:
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
euler = euler + 1
print(total)
233168
# Replace the increment with variable name += increment.
n = 1000
total = 0
euler = 0
while euler < n:
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
euler += 1
print(total)
233168
# Don't stop at one bug.
# Replace the increment with variable name += increment.
# This time with accumulating the total.
n = 1000
total = 0
euler = 0
while euler < n:
if (euler % 3 == 0) | (euler % 5 == 0):
total += euler
euler += 1
print(total)
233168
# Replace | with or for readability.
# It's more than readability, it's the wrong operator.
# This is a bitwise or (0 or 1). It will always program both sides of the equation.
# 'or' compares to False. This is safer if I could get per say a div/0.
n = 1000
total = 0
euler = 0
while euler < n:
if (euler % 3 == 0) or (euler % 5 == 0):
total += euler
euler += 1
print(total)
233168
def foo(total):
#total = 0
for euler in range(1000):
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
#print(total)
import timeit
%timeit foo(0)
1000 loops, best of 3: 281 µs per loop
total = 0
for euler in range(1000):
if (euler % 3 == 0) | (euler % 5 == 0):
total = total + euler
print(total)
233168
def foo(n):
total = 0
for euler in range(n):
if (euler % 3 == 0) or (euler % 5 == 0):
total = total + euler
return total
n = 10
foo(n)
23
n = 1000
%timeit foo(n)
foo(n)
1000 loops, best of 3: 208 µs per loop
233168
def foo(n):
total = 0
for i in range(n):
if (i % 3 == 0) or (i % 5 == 0):
total += i
return total
n = 1000
%timeit foo(n)
foo(n)
1000 loops, best of 3: 209 µs per loop
233168