-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1
More file actions
executable file
·28 lines (22 loc) · 811 Bytes
/
problem1
File metadata and controls
executable file
·28 lines (22 loc) · 811 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/python
# problem: Add all the natural numbers below one thousand that are multiples of 3 or 5.
# this is more efficient to write, but runs slower since it iterates over the set of numbers twice -- once to filter and once to sum
numberSet = range(1, 1000)
multiples = filter(lambda x: x % 3 == 0 or x % 5 == 0, numberSet)
print sum(multiples)
# this was my first attempt, only requires iteration over the list once
total = 0
for value in range(1, 1000):
if value % 3 == 0 or value % 5 == 0:
total += value
print total
# this recognizes the mathematical properties of the problem
total = 0
max = 999
maxFor3 = 999 / 3
maxFor5 = 999 / 5
maxFor15 = 999 / 15
total += 3 * maxFor3 * (maxFor3 + 1)/2
total += 5 * maxFor5 * (maxFor5 + 1)/2
total -= 15 * maxFor15 * (maxFor15 + 1)/2
print total