-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler023.py
executable file
·51 lines (37 loc) · 1.51 KB
/
euler023.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/python
from primes import getDivisors
import sys
if sys.version_info[0] == 2:
# get rid of 2.x range that produced list instead of iterator
range = xrange
def genAbundantNums(aMax):
# generate all the abundant numbers <= aMax
for a in range(12, aMax + 1):
if sum(getDivisors(a, proper=True)) > a:
yield a
def isSumOf(n, testSet, numElements=2):
# return true if n is a sum of numElements from testSet
if numElements == 2:
return any( (n - checkElement in testSet) for checkElement in testSet)
else:
numCheck = numElements - 1
return any( isSumOf(n - checkElement, testSet, numCheck)
for checkElement in testSet )
def genNonSums(maxNumCheck, testSet, numElements=2):
# generate numbers that aren't sums of two abundant numbers
minCheckSum = min(testSet) * numElements
for n in range(1, minCheckSum):
yield n
for n in range(minCheckSum, maxNumCheck + 1):
if not isSumOf(n, testSet, numElements):
yield n
def euler23(maxNumCheck=28123, numSum=2):
# get all the abundant numbers that could be relevant for finding natural
# numbers that can't be expressed as sum of numSum abundant numbers
abundantNums = set(genAbundantNums(maxNumCheck - 12))
# get the sum of all the numbers that aren't the sum of numSum abundantNums
sumOfNonSums = sum(genNonSums(maxNumCheck, abundantNums, numSum))
print('Sum of all numbers not expressable as sum of %d abundant numbers is %d'
% (numSum, sumOfNonSums))
if __name__ == "__main__":
euler23()