# Solutions to Project Euler's first 50 problems

These are codes to solve the first 50 problems in Project Euler. The thing is that I try to make these python codes give solutions in less than 1 second. This is achieved by using the excellent numba package. This post is written in an IPython notebook.

In [1]:
# !mkdir pe
In [2]:
def problem1():
n = 1000
s = 0
for i in range(1, n):
if i % 3 == 0 or i % 5 == 0:
s += i
return s

print(problem1())
%timeit problem1()
233168
1000 loops, best of 3: 245 µs per loop
In [3]:
def problem2():
n = 4000000
s = 0
a, b = 1, 2
while a <= n:
if a % 2 == 0:
s += a
a, b = b, a+b
return s

print(problem2())
%timeit problem2()
4613732
100000 loops, best of 3: 8.44 µs per loop
In [4]:
def problem3():
n = 600851475143
i = 1
while n != 1:
i += 1
while n % i == 0:
n = n // i
return i

print(problem3())
%timeit problem3()
6857
1000 loops, best of 3: 1.68 ms per loop
In [5]:
def problem4():
m = 10000
for i in range(100, 1000):
for j in range(i, 1000):
p = i * j
if str(p) == str(p)[::-1] and p > m:
m = p
return m

print(problem4())
%timeit problem4()
906609
1 loop, best of 3: 352 ms per loop
In [6]:
def common_divisor(a, b):
while a != 0:
a, b = b%a, a
return b

def problem5():
n = 20
p = 1
for i in range(2, n+1):
p = (p * i) // common_divisor(p, i)
return p

print(problem5())
%timeit problem5()
232792560
100000 loops, best of 3: 15.9 µs per loop
In [7]:
def problem6():
n = 100
s = 0
for i in range(1, n):
for j in range(i+1, n+1):
s += i * j
return 2 * s

print(problem6())
%timeit problem6()
25164150
1000 loops, best of 3: 530 µs per loop
In [8]:
import numpy as np
from numba import jit

@jit
def sieveEratosthenes(n):
s = np.ones(n+1)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

@jit
def problem7():
n = 10001
limit = 10**6
sieve = sieveEratosthenes(limit)
c = 0
for i in range(len(sieve)):
if sieve[i] == 1:
c += 1
if c == n:
return i

print(problem7())
%timeit problem7()
104743
10 loops, best of 3: 27.3 ms per loop
In [9]:
%%file pe/problem8.txt
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Overwriting pe/problem8.txt
In [10]:
def problem8():
a = []
with open('pe/problem8.txt') as f:
for line in f:
a.append(line.rstrip('\n'))
m = 0
for n in range(996):
p = 1
for i in range(5):
p *= int(a[(n+i)//50][(n+i)%50])
if p > m:
m = p
return m

print(problem8())
%timeit problem8()
40824
100 loops, best of 3: 4.2 ms per loop
In [11]:
def problem9():
n = 1000
for b in range(1, n//2):
for a in range(1, n-2*b):
c = 1000 - a - b
if a**2 + b**2 == c**2:
return a*b*c

print(problem9())
%timeit problem9()
31875000
1 loop, best of 3: 229 ms per loop
In [12]:
import numpy as np
from numba import jit, int64

@jit
def sieveEratosthenes(n):
s = np.ones(n+1, dtype=np.int8)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

@jit(locals={'s': int64})
def problem10():
n = 2000000
sieve = sieveEratosthenes(n-1)
s = 0
for i in range(len(sieve)):
if sieve[i] == 1:
s += i
return s

print(problem10())
%timeit problem10()
142913828922
100 loops, best of 3: 9.03 ms per loop
In [13]:
%%file pe/problem11.txt
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
Overwriting pe/problem11.txt
In [14]:
def problem11():
a = []
with open('pe/problem11.txt') as f:
for line in f:
a.append([int(x) for x in line.split()])
for i in range(20):
a[i] = [0, 0, 0] + a[i] + [0, 0, 0]
for j in range(3):
a.append([0] * 26)
m = 0
for i in range(20):
for j in range(3, 20):
r = c = dr = dl = a[i][j]
for k in range(1, 4):
r *= a[i][j+k]
c *= a[i+k][j]
dr *= a[i+k][j+k]
dl *= a[i+k][j-k]
m1 = max(r, c, dr, dl)
if m1 > m:
m = m1
return m

print(problem11())
%timeit problem11
70600674
The slowest run took 45.10 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 27.3 ns per loop
In [15]:
from numba import jit

@jit
def find_num_divisor(n):
s = 1
while n % 2 == 0:
n //= 2
s += 1
i = 3
while i <= n:
c = 0
while n % i == 0:
n //= i
c += 1
s *= (c + 1)
i += 2
return s

@jit
def problem12():
n = 500
s = 1
i = 1
while find_num_divisor(s) <= n:
i += 1
s += i
return s

print(problem12())
%timeit problem12()
76576500
10 loops, best of 3: 161 ms per loop
In [16]:
%%file pe/problem13.txt
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
Overwriting pe/problem13.txt
In [17]:
def problem13():
a = []
with open('pe/problem13.txt') as f:
for line in f:
a.append(int(line.rstrip('\n')))
return int(str(sum(a))[:10])

print(problem13())
%timeit problem13()
5537376230
1000 loops, best of 3: 262 µs per loop
In [18]:
import numpy as np
from numba import jit

@jit
def problem14():
n = 1000000
table = np.zeros(n)
table[1] = 1
for i in range(2, n):
t = i
c = 0
while t >= i:
c += 1
if t % 2 == 0:
t //= 2
else:
t = 3 * t + 1
table[i] = c + table[t]
m = 0
r = 0
for i in range(n):
if table[i] > m:
m = table[i]
r = i
return r

print(problem14())
%timeit problem14()
837799
10 loops, best of 3: 31.6 ms per loop
In [19]:
from math import factorial

def problem15():
m = n = 20
return factorial(m+n) // (factorial(m) * factorial(n))

print(problem15())
%timeit problem15()
137846528820
The slowest run took 4.87 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.11 µs per loop
In [20]:
def problem16():
n = 1000
return sum([int(x) for x in str(2**n)])

print(problem16())
%timeit problem16()
1366
10000 loops, best of 3: 123 µs per loop
In [21]:
table = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven',
12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen',
16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen',
20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty',
70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred',
1000: 'thousand'}

def word(n):
if n == 1000:
return table[1] + table[1000]
r = table[0]
if n >= 100:
r += table[n//100] + table[100]
if n % 100 == 0:
return r
else:
r += 'and'
n = n % 100
if n >= 20:
return r + table[(n//10)*10] + table[n%10]
return r + table[n]

def problem17():
return sum([len(word(n)) for n in range(1, 1001)])

print(problem17())
%timeit problem17()
21124
1000 loops, best of 3: 1.84 ms per loop
In [22]:
%%file pe/problem18.txt
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
Overwriting pe/problem18.txt
In [23]:
def problem18():
a = []
with open('pe/problem18.txt') as f:
for line in f:
a.append([int(x) for x in line.split()])
n = len(a)
for i in range(n-2, -1, -1):
for j in range(i+1):
a[i][j] = a[i][j] + max(a[i+1][j], a[i+1][j+1])
return a[0][0]

print(problem18())
%timeit problem18()
1074
The slowest run took 12.25 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 271 µs per loop
In [24]:
from datetime import date

def problem19():
c = 0
for y in range(1901, 2001):
for m in range(1, 13):
if date(y, m, 1).weekday() == 6:
c += 1
return c

print(problem19())
%timeit problem19()
171
1000 loops, best of 3: 571 µs per loop
In [25]:
from math import factorial

def problem20():
n = 100
return sum([int(x) for x in str(factorial(n))])

print(problem20())
%timeit problem20()
648
10000 loops, best of 3: 55.2 µs per loop
In [26]:
def d(n):
if n == 1:
return 0
s = 1
squaren = int(n**0.5)
for i in range(2, squaren+1):
if n % i == 0:
s += (i + n // i)
if n == squaren ** 2:
s -= squaren
return s

def problem21():
n = 10000
s = 0
for i in range(2, n):
t = d(i)
if t != i and d(t) == i:
s += i
return s

print(problem21())
%timeit problem21()
31626
1 loop, best of 3: 189 ms per loop
In [27]:
from urllib.request import urlopen
from contextlib import closing

with closing(urlopen('https://projecteuler.net/project/resources/p022_names.txt')) as u:
with open('pe/problem22.txt', 'wb') as f:
f.write(data)
print('Writing pe/problem22.txt')
Writing pe/problem22.txt
In [28]:
def value(name):
return sum([ord(x) - ord('A') + 1 for x in name])

def problem22():
with open('pe/problem22.txt') as f:
a.sort()
s = 0
for i in range(len(a)):
s += ((i + 1) * value(a[i]))
return s

print(problem22())
%timeit problem22()
871198282
10 loops, best of 3: 19.5 ms per loop
In [29]:
import numpy as np
from numba import jit

@jit
def is_abundant(n):
if n == 1:
return 0
s = 1
squaren = int(n**0.5)
for i in range(2, squaren+1):
if n % i == 0:
s += (i + n // i)
if n == squaren ** 2:
s -= squaren
if s > n:
return 1
return 0

@jit
def problem23():
n = 28123
a = []
for i in range(1, n):
if is_abundant(i):
a.append(i)
newa = np.empty(len(a), dtype=np.int32)
for i in range(len(a)):
newa[i] = a[i]
b = np.zeros(n+1, dtype=np.int8)
for i in range(newa.size):
for j in range(i, newa.size):
if newa[i] + newa[j] > n:
break
b[newa[i] + newa[j]] = 1
s = 0
for i in range(1, n+1):
if b[i] == 0:
s += i
return s

print(problem23())
%timeit problem23()
4179871
10 loops, best of 3: 63.9 ms per loop
In [30]:
from math import factorial

def problem24():
n = 1000000
a = []
b = set(range(10))
for i in range(9, -1, -1):
c = sorted(b)
t = (n-1) // factorial(i)
a.append(c[t])
b.remove(c[t])
n -= (t * factorial(i))
return ''.join([str(x) for x in a])

print(problem24())
%timeit problem24()
2783915460
10000 loops, best of 3: 25.8 µs per loop
In [31]:
from math import log10

def problem25():
n = 1000
a, b = 1, 1
c = 2
while int(log10(b)) + 1 < n:
a, b = b, a+b
c += 1
return c

print(problem25())
%timeit problem25()
4782
100 loops, best of 3: 3.9 ms per loop
In [32]:
from numba import jit

@jit
def length_cycle(n):
a = [1]
i = 1
while True:
i = (i * 10) % n
if i in a:
return len(a) - a.index(i)
a.append(i)

@jit
def problem26():
n = 1000
l = 0
m = 1
for i in range(2, n):
t = length_cycle(i)
if t > l:
l = t
m = i
return m

print(problem26())
%timeit problem26()
983
10 loops, best of 3: 15.7 ms per loop
In [33]:
import numpy as np
from numba import jit

@jit
def sieveEratosthenes(n):
s = np.ones(n+1)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

@jit
def problem27():
n = 1000
sieve = sieveEratosthenes(2*(n-1)**2 + n-1)
result = 0
max_length = 0
min_a = -((n // 2) * 2 - 1)
max_a = (n // 2) * 2 + 1
for b in range(n):
if sieve[b] == 1:
for a in range(min_a, max_a, 2):
l = 0
p = b
while p >= 0 and sieve[p] == 1:
l += 1
p = l**2 + a*l + b
if l > max_length:
max_length = l
result = a * b
return result

print(problem27())
%timeit problem27()
-59231
10 loops, best of 3: 63.6 ms per loop
In [34]:
def problem28():
n = 1001
s = 1
for i in range(3, n+1, 2):
a1 = i**2
a2 = a1 - i + 1
a3 = a2 - i + 1
a4 = a3 - i + 1
s += (a1 + a2 + a3 + a4)
return s

print(problem28())
%timeit problem28()
669171001
1000 loops, best of 3: 463 µs per loop
In [35]:
def problem29():
n = 100
s = set()
for a in range(2, n+1):
for b in range(2, n+1):
return len(s)

print(problem29())
%timeit problem29()
9183
100 loops, best of 3: 11.3 ms per loop
In [36]:
from itertools import combinations_with_replacement

def problem30():
n = 5
s = 0
for i in range(2, n+2):
for com in combinations_with_replacement(range(10), i):
t = sum([x**n for x in com])
if sorted(com) == sorted([int(x) for x in str(t)]):
s += t
return s

print(problem30())
%timeit problem30()
443839
10 loops, best of 3: 82.5 ms per loop
In [37]:
def check(n, coins):
if n == 0 or coins[0] == 1:
return 1
c = 0
for i in range(len(coins)):
m = n - coins[i]
if m >= 0:
c += check(m, coins[i:])
return c

def problem31():
n = 200
coins = [200, 100, 50, 20, 10, 5, 2, 1]
return check(n, coins)

print(problem31())
%timeit problem31()
73682
1 loop, best of 3: 138 ms per loop
In [38]:
def problem32():
s = set()
for i in range(10, 100):
for j in range(100, 1000 // i + 1):
p = i * j
if ''.join(sorted(str(i) + str(j) + str(p))) == '123456789':
for i in range(1, 10):
for j in range(1000, 10000 // i + 1):
p = i * j
if ''.join(sorted(str(i) + str(j) + str(p))) == '123456789':
return sum(s)

print(problem32())
%timeit problem32()
14804
10 loops, best of 3: 60.4 ms per loop
In [39]:
def common_divisor(a, b):
while a != 0:
a, b = b%a, a
return b

def problem33():
p, q = 1, 1
for i in range(10, 100):
i1 = int(str(i)[0])
i2 = int(str(i)[1])
if i % 10 == 0 or i1 == i2:
continue
for j in range(i+1, 100):
j1 = int(str(j)[0])
j2 = int(str(j)[1])
if j % 10 == 0 or j1 == j2:
continue
if ((i1 == j2 and i * j1 == j * i2) or
(i2 == j1 and i * j2 == j * i1)):
p *= i
q *= j
return q // common_divisor(p, q)

print(problem33())
%timeit problem33()
100
100 loops, best of 3: 5.37 ms per loop
In [40]:
from math import factorial
from itertools import combinations_with_replacement

def problem34():
s = 0
max_digits = 7
for i in range(2, max_digits+1):
for com in combinations_with_replacement(range(10), i):
t = sum([factorial(x) for x in com])
if sorted(com) == sorted([int(x) for x in str(t)]):
s += t
return s

print(problem34())
%timeit problem34()
40730
10 loops, best of 3: 150 ms per loop
In [41]:
from numba import jit

@jit
def sieveEratosthenes(n):
s = [1] * (n + 1)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

def problem35():
n = 1000000
test_list = ['0', '2', '4', '5', '6', '8']
sieve = sieveEratosthenes(n-1)
c = 4
for p in range(10, n):
if sieve[p] == 1:
str_p = str(p)
flag = 1
for x in test_list:
if x in str_p:
flag = 0
break
if flag == 0:
continue
for i in range(1, len(str_p)):
p1 = int(''.join(str_p[i:] + str_p[:i]))
if sieve[p1] == 0:
flag = 0
break
if flag == 1:
c += 1
return c

print(problem35())
%timeit problem35()
55
1 loop, best of 3: 222 ms per loop
In [42]:
def problem36():
s = 0
for i in range(1, 100000):
str_i = str(i)
if str_i == str_i[::-1]:
str_bin_i = bin(i)[2:]
if str_bin_i == str_bin_i[::-1]:
s += i
for j in range(100, 1000):
i = int(str(j) + str(j)[::-1])
str_bin_i = bin(i)[2:]
if str_bin_i == str_bin_i[::-1]:
s += i
return s

print(problem36())
%timeit problem36()
872187
10 loops, best of 3: 71.8 ms per loop
In [43]:
def isPrime(n):
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
k = int(n**0.5)
i = 3
while i <= k:
if n % i == 0:
return False
i += 2
return True

def isLeftRightTruncatePrime(n):
if n < 10:
return False
k = n
while k > 0:
if not isPrime(k):
return False
k = k // 10
k = n
while k >= 10:
k = int(str(k)[1:])
if not isPrime(k):
return False
return True

def problem37():
s = 0
count = 0
for i in [23, 37, 53, 73, 373, 313, 3173]:
if isLeftRightTruncatePrime(i) == 1:
s += i
count += 1
first = ["31", "7", "37"]
second = [""]
third = ["7", "373", "13"]
while count < 11:
for i in first:
for j in second:
for k in third:
n = int(i+j+k)
if isLeftRightTruncatePrime(n):
s += n
count += 1
term = [j+"3" for j in second] + [j+"9" for j in second]
second = term[:]
return s

print(problem37())
%timeit problem37()
748317
10 loops, best of 3: 36.5 ms per loop
In [44]:
def isPandigital(n):
return len(str(n)) == 9 and set(str(n)) == set("123456789")

def problem38():
l = []
for i in range(1, 10):
s = ""
for j in range(1, 10):
s += str(i*j)
if isPandigital(s):
l.append(int(s))
for i in range(10, 100):
s = ""
for j in range(1, 5):
s += str(i*j)
if isPandigital(s):
l.append(int(s))
for i in range(100, 1000):
s = ""
for j in range(1, 4):
s += str(i*j)
if isPandigital(s):
l.append(int(s))
for i in range(1000, 10000):
s = ""
for j in range(1, 3):
s += str(i*j)
if isPandigital(s):
l.append(int(s))
return max(l)

print(problem38())
%timeit problem38()
932718654
10 loops, best of 3: 31 ms per loop
In [45]:
def problem39():
d = dict()
for i in range(1, 500):
for j in range(1, 500):
k2 = i**2 + j**2
k = int(k2**0.5)
if k2 == k**2:
p = i + j + k
if p in d:
d[i+j+k] += 1
else:
d[i+j+k] = 0
return max(d, key=d.get)

print(problem39())
%timeit problem39()
840
1 loop, best of 3: 489 ms per loop
In [46]:
def findDigit(n):
i = 1
s = 0
while i <= n:
s += len(str(i))
if s >= n:
break
i += 1
return int(str(i)[-(s - n + 1)])

def problem40():
s = 1
for i in range(0, 7):
s *= findDigit(10**i)
return s

print(problem40())
%timeit problem40()
210
10 loops, best of 3: 173 ms per loop
In [47]:
from itertools import permutations

def isPrime(n):
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
k = int(n**0.5)
i = 3
while i <= k:
if n % i == 0:
return False
i += 2
return True

def problem41():
pandigital_prime = []
for i in [4, 7]:
s = ""
for j in range(1, i+1):
s += str(j)
for item in permutations(s, i):
n = int(''.join(item))
if isPrime(n):
pandigital_prime.append(n)
return max(pandigital_prime)

print(problem41())
%timeit problem41()
7652413
1 loop, best of 3: 232 ms per loop
In [48]:
from urllib.request import urlopen
from contextlib import closing

with closing(urlopen('https://projecteuler.net/project/resources/p042_words.txt')) as u:
with open('pe/problem42.txt', 'wb') as f:
f.write(data)
print('Writing pe/problem42.txt')
Writing pe/problem42.txt
In [49]:
def problem42():
with open('pe/problem42.txt') as f:
maxN = int((max([len(x) for x in listWords]) * 26)**0.5)
listTriangle = [i*(i+1)//2 for i in range(1, maxN)]
c = 0
for word in listWords:
value = sum([ord(x) - ord('A') + 1 for x in word])
if value in listTriangle:
c += 1
return c

print(problem42())
%timeit problem42()
162
100 loops, best of 3: 7.27 ms per loop
In [50]:
from itertools import permutations

def problem43():
s = 0
for i in range(6, 999//17 + 1):
d8910 = list(str(i * 17))
if '5' not in d8910 and len(set(d8910)) == 3:
remain = list('012346789')
for x in d8910:
remain.remove(x)
for n in permutations(remain, 6):
if n[0] != '0':
n = list(n)
n.insert(5, '5')
n.extend(d8910)
primes = [2, 3, 5, 7, 11, 13, 17]
flag = True
for i in range(7):
if int(''.join(n[i+1:i+4])) % primes[i] != 0:
flag = False
break
if flag == True:
s += int(''.join(n))
return s

print(problem43())
%timeit problem43()
16695334890
10 loops, best of 3: 91 ms per loop
In [51]:
# not so right answer, solve the problem of minimizing the max of P_k and P_j
from numba import jit

@jit
def isPentagonal(n):
return ((24*n+1)**0.5+1)/6 % 1 == 0

@jit
def problem44():
n = 2
listPentagonal = [1]
diff = []
while True:
listPentagonal.append(n*(3*n-1)/2)
diff.append(0)
inc = 3*n-2
for i in range(n-1):
diff[i] += inc
if isPentagonal(diff[i]) and isPentagonal(listPentagonal[i] + listPentagonal[n-1]):
return diff[i]
n += 1

print(problem44())
%timeit problem44()
5482660
10 loops, best of 3: 81.2 ms per loop
In [52]:
def isPentagonal(n):
return ((24*n+1)**0.5+1)/6 % 1 == 0

def isHexagonal(n):
return ((8*n+1)**0.5+1)/4 % 1 == 0

def problem45():
n = 286
while True:
t = n*(n+1)//2
if isHexagonal(t) and isPentagonal(t):
return t
n += 1

print(problem45())
%timeit problem44()
1533776805
10 loops, best of 3: 86.8 ms per loop
In [53]:
def isPrime(n):
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
k = int(n**0.5)
i = 3
while i <= k:
if n % i == 0:
return False
i += 2
return True

def problem46():
n = 35
listOddPrime = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
while True:
if isPrime(n):
listOddPrime.append(n)
else:
flag = False
for x in listOddPrime:
if ((n-x)/2)**0.5 % 1 == 0:
flag = True
if flag == False:
return n
n += 2

print(problem46())
%timeit problem46()
5777
1 loop, best of 3: 410 ms per loop
In [54]:
from numba import jit

@jit
def check(n):
s = 0
if n % 2 == 0:
s = 1
n = n // 2
while n % 2 == 0:
n = n // 2
i = 3
while i*i <= n and s<4:
if n % i == 0:
s += 1
n = n // i
while n % i == 0:
n = n // i
i += 2
if (n>1 and s==3) or (n==1 and s==4):
return True
return False

@jit
def problem47():
a,b,c,d = (False, False, False, False)
n = 1
while True:
a,b,c,d = b,c,d,check(n+3)
if a and b and c and d:
return n
n += 1

print(problem47())
%timeit problem47()
134043
10 loops, best of 3: 77.3 ms per loop
In [55]:
def problem48():
s = 0
for i in range(1, 1001):
s += (i**i)%(10**10)
return s % (10**10)

print(problem48())
%timeit problem48()
9110846700
100 loops, best of 3: 13.8 ms per loop
In [56]:
import numpy as np
from itertools import permutations

def sieveEratosthenes(n):
s = np.ones(n+1, dtype=np.int8)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

def checkCondition(n, sieve):
listPermutation = [int(''.join(x)) for x in permutations(str(n))]
listPrime = sorted([x for x in listPermutation if sieve[x] == 1 and x != n])
for i in range(len(listPrime) - 1):
for j in range(i+1, len(listPrime)):
if 2*listPrime[i] == n + listPrime[j]:
return True
return False

def problem49():
sieve = sieveEratosthenes(10000)
for n in range(1001,10000):
if sieve[n] == 1 and checkCondition(n, sieve):
if n != 1487:
return n

print(problem49())
%timeit problem49()
2969
10 loops, best of 3: 31.7 ms per loop
In [57]:
import numpy as np
from numba import jit

@jit
def sieveEratosthenes(n):
s = np.ones(n+1, dtype=np.int8)
s[0] = 0
s[1] = 0
for i in range(2, int(n**0.5)+1):
if s[i] == 1:
for j in range(2, (n//i)+1):
s[i*j] = 0
return s

@jit
def problem50():
sieve = sieveEratosthenes(10**6)
lenPrime = 0
for i in range(len(sieve)):
if sieve[i] == 1:
lenPrime += 1
listPrime = np.zeros(lenPrime, dtype=np.int32)
j = 0
for x in range(len(sieve)):
if sieve[x] == 1:
listPrime[j] = x
j += 1
maxL = 21
r = 953
for i in range(len(listPrime) - 21):
s = listPrime[i]
for j in range(i+1, i+22):
s += listPrime[j]
c = 22
while s < 10**6 and (i+c < len(listPrime)):
if sieve[s] == 1 and c > maxL:
maxL = c
r = s
s += listPrime[i+c]
c += 1
return r

print(problem50())
%timeit problem50()
997651
100 loops, best of 3: 9.99 ms per loop