/
problems_41_60.py
481 lines (389 loc) · 13.7 KB
/
problems_41_60.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python
import sys
import os
import math
import time
import itertools
import mathlib as mlib
from mathlib import *
from number_theory import *
def problem41():
# must have < 9 digits, 9-pandigit is div by 9
digits = '12345678'
max_p = 0
for i in range(8, 1, -1):
gen = mlib.gen_permutation(digits[:i])
while True:
try:
p = gen.next()
if mlib.is_prime(int(p)) and int(p) > max_p:
max_p = int(p)
except StopIteration:
break
return max_p
def problem42():
""" Using words.txt (right click and 'Save Link/Target As...'), a 16K
text file containing nearly two-thousand common English words, how many
are triangle words? """
def get_ascii_value(word):
return sum([(ord(c)-64) for c in word])
def get_triangle_nums():
map = {}
for i in range(1, 1000):
map[(i * (i+1) / 2)] = 1
return map
triangle_num = get_triangle_nums()
fin = open('files/p42_words')
lines = fin.readlines()
words = lines[0].replace('"', '').split(',')
count = 0
for word in words:
if get_ascii_value(word) in triangle_num:
count += 1
return count
def problem43():
""" The number, 1406357289, is a 0 to 9 pandigital number because it is
made up of each of the digits 0 to 9 in some order, but it also has a
rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we
note the following:
d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is
divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by
11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the
sum of all 0 to 9 pandigital numbers with this property. """
def calculate(nums, divisor, level):
new_nums = []
for n in nums:
for i in range(0, 10):
k = i*(10**(level-1)) + int(n)
if (k / (10**(level-3))) % divisor == 0:
new_nums.append(k)
return new_nums
nums = [str(k) for k in range(100, 999) if k % 17 == 0]
divs = (13, 11, 7, 5, 3, 2, 1)
level = 4
for d in divs:
nums = calculate(nums, d, level)
level += 1
pandigital = [n for n in nums if mlib.is_pandigital(n, 10)]
return sum(pandigital)
def problem44():
"""
Pentagonal numbers are generated by the formula, P_(n)=n(3n\u22121)/2.
The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P_(4) + P_(7) = 22 + 70 = 92 = P_(8). However,
their difference, 70 \u2212 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P_(j) and P_(k), for which their
sum and difference is pentagonal and D = |P_(k) \u2212 P_(j)| is
minimised; what is the value of D?
"""
def create_pentagonal(n):
return [(n*(3*n-1)/2) for n in range(1, n)]
pen_map = {}
pentagonal = create_pentagonal(10**4)
for p in pentagonal:
pen_map[p] = 1
for i in range(len(pentagonal)):
for j in range(0, i):
if (pentagonal[i] + pentagonal[j]) not in pen_map:
continue
if (pentagonal[i] - pentagonal[j]) in pen_map:
return pentagonal[i] - pentagonal[j]
def problem45():
pen_map = {}
hex_map = {}
i = 1
while True:
i += 1
pen_map[i*(3*i-1)/2] = i
hex_map[i*(2*i-1)] = i
t = (i*(i+1)/2)
if t in hex_map and t in pen_map:
if i > 285:
return t
def problem46():
"""
It was proposed by Christian Goldbach that every odd composite
number can be written as the sum of a prime and twice a square.
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as
the sum of a prime and twice a square?
"""
prime_map = prime_sieve(1000000, output={})
sq_map = {}
for i in range(0, 10000):
sq_map[i] = i**2
n = 3
while True:
n += 2
if n in prime_map:
continue
m = 1
is_goldbach = False
while 2*m < n:
if (n-sq_map[m]*2) in prime_map:
is_goldbach = True
m += 1
if not is_goldbach:
return n
def problem47():
max = 10**6
pmap = [0 for i in range(max)]
for i in range(2, int(math.sqrt(max))):
if not mlib.is_prime(i):
continue
k = i
while k < len(pmap):
pmap[k] += 1
k += i
for i in range(10, len(pmap), 4):
if pmap[i] == 4:
if pmap[i+1] == 4 and pmap[i+2] == 4 and pmap[i+3] == 4:
return i
if pmap[i-1] == 4 and pmap[i-2] == 4 and pmap[i-3] == 4:
return i-3
def problem48():
"""
Find the last ten digits of the series:
1^(1) + 2^(2) + 3^(3) + ... + 1000^(1000).
"""
return str(sum([i**i for i in range(1, 1001)]))[-10:]
def problem49():
"""
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms
increases by 3330, is unusual in two ways: (i) each of the three terms
are prime, and, (ii) each of the 4-digit numbers are permutations of
one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit
primes, exhibiting this property, but there is one other 4-digit
increasing sequence.
What 12-digit number do you form by concatenating the three terms
in this sequence?
"""
start_n = 1491
end_n = 9999
prime_map = mlib.prime_sieve(10**5, output={})
for n in range(start_n, end_n, 2):
for step in range(2, (end_n-n)/2, 2):
if (n in prime_map and n+step in prime_map and
n+step*2 in prime_map):
n1 = list(str(n))
n2 = list(str(n+step))
n3 = list(str(n+2*step))
n1.sort()
n2.sort()
n3.sort()
if n1 == n2 and n2 == n3:
return str(n)+str(n+step)+str(n+2*step)
def problem50():
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime
below one-hundred.
The longest sum of consecutive primes below one-thousand that adds
to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the
most consecutive primes?
"""
prime_list = prime_sieve(10**6, output=[])
prime_map = {}
for p in prime_list:
prime_map[p] = True
max_p = 2
max_len = 1
max = 10**6
for i in range(0, len(prime_list)):
index = i
plen = 0
psum = 0
while psum < max and index < len(prime_list):
psum += prime_list[index]
plen += 1
if psum in prime_map:
if plen > max_len:
max_len = plen
max_p = psum
index += 1
return max_p
def problem51():
"""
By replacing the 1^(st) digit of *57, it turns out that six of the
possible values: 157, 257, 457, 557, 757, and 857, are all prime.
By replacing the 3^(rd) and 4^(th) digits of 56**3 with the same
digit, this 5-digit number is the first example having seven primes,
yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and
56993. Consequently 56003, being the first member of this family,
is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number
(not necessarily adjacent digits) with the same digit, is part
of an eight prime value family.
"""
def replace_n(n, c):
return sum([miller_rabin(int(str(n).replace(c, str(x)))) for x in range(1,10)])
primes = [x for x in prime_sieve(10**6, output=[]) if x > 10000]
for p in primes:
for x in range(1, 10):
if str(p).find(str(x)) >= 0 and replace_n(p, str(x)) > 7:
return p
return None
def problem52():
""" It can be seen that the number, 125874, and its double, 251748,
contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x,
contain the same digits. """
i = 1
while True:
i += 1
# optimize: jump to valid portion
if len(str(i)) != len(str(i*6)):
i = 10**len(str(i))
continue
s1 = list(str(i))
s1.sort()
found = True
for x in [2,3,4,5,6]:
sx = list(str(i*x))
sx.sort()
if sx != s1:
found = False
break
if found:
return i
def problem53():
"""How many, not necessarily distinct, values of nCr, for 1 n 100, are
greater than one-million? """
cutoff = 10**6
fac_map = {}
count = 0
for i in range(1, 101):
fac_map[i] = factorial(i)
for n in range(1, 101):
for r in range(1, n):
c_nr = fac_map[n] / fac_map[r] / fac_map[n-r]
if c_nr > cutoff:
count += 1
return count
def problem54():
""" The file, poker.txt, contains one-thousand random hands dealt to two
players. Each line of the file contains ten cards (separated by a single
space): the first five are Player 1's cards and the last five are Player
2's cards. You can assume that all hands are valid (no invalid
characters or repeated cards), each player's hand is in no specific
order, and in each hand there is a clear winner.
How many hands does Player 1 win? """
pass
def problem55():
""" A number that never forms a palindrome through the reverse and add
process is called a Lychrel number. How many Lychrel numbers are there
below ten-thousand? """
count = 0
i = 0
while i < 10**4:
i += 1
n = i
is_lychrel = True
for j in range(0, 50):
n += mlib.reverse_number(n)
if is_palindrome(str(n)):
is_lychrel = False
break
if is_lychrel:
count += 1
return count
def problem56():
""" Considering natural numbers of the form, ab, where a, b 100, what is
the maximum digital sum? """
max_sum = 0
for a in range(2, 100):
c = a
for b in range(2, 100):
c *= a
s = sum([int(x) for x in str(c)])
if s > max_sum:
max_sum = s
return max_sum
def problem57():
"""
3/2 1
7/5 2
17/12 5
41/29 12
99/70 29
239/169 70
577/408 169
generalize:
D_i = N_i-1 + D_i-1
N_i = N_i-1 + D_i-1*2
In the first one-thousand expansions, how many fractions contain a
numerator with more digits than denominator?
"""
n_i = 3
d_i = 2
count = 0
for i in range(0, 10**3):
n_i = n_i + d_i*2
d_i = n_i - d_i
if len(str(n_i)) > len(str(d_i)):
count += 1
return count
def problem58():
""" Starting with 1 and spiralling anticlockwise in the following way, a
square spiral with side length 7 is formed. If one complete new layer is
wrapped around the spiral above, a square spiral with side length 9 will
be formed. If this process is continued, what is the side length of the
square spiral for which the ratio of primes along both diagonals first
falls below 10%? """
prime_map = mlib.prime_sieve(2*10**6)
side_len = 3
num_prime = 0.0
num = 0
while side_len < 20000:
c = side_len**2
corners = [n for n in range(c, c - side_len*3, -side_len+1)]
num += len(corners)
for p in corners:
if p in prime_map:
num_prime += 1
if num_prime / num < 0.1:
return side_len
side_len += 2
def problem59():
""" Your task has been made easy, as the encryption key consists of
three lower case characters. Using cipher1.txt (right click and 'Save
Link/Target As...'), a file containing the encrypted ASCII codes, and
the knowledge that the plain text must contain common English words,
decrypt the message and find the sum of the ASCII values in the original
text. """
fin = open('files/p59_ciphers')
lines = fin.readlines()
cipher = []
for n in lines[0].split(','):
cipher.append(int(n))
cipher.extend([0, 0])
keys = range(ord('a'), ord('z')+1)
for cipher_key in itertools.permutations(keys, 3):
plain_text = ""
for n in range(0, len(cipher)-1, 3):
a = cipher[n] ^ cipher_key[0]
b = cipher[n+1] ^ cipher_key[1]
c = cipher[n+2] ^ cipher_key[2]
plain_text += chr(a) + chr(b) + chr(c)
if plain_text.find(' the ') > -1:
value = sum([ord(c) for c in plain_text[:-2]])
return value
def problem60():
""" Find the lowest sum for a set of five primes for which any two
primes concatenate to produce another prime. """
"""
prime_map = mlib.prime_sieve(2*10**6)
prime_list = mlib.prime_sieve(10**4, [])
#print prime_list
prime_list = [str(p) for p in prime_list]
for i in range(1, len(prime_list)):
if int(prime_list[1] + prime_list[i]) in prime_map:
if int(prime_list[i] + prime_list[1]) in prime_map:
print prime_list[i]
"""
pass