-
Notifications
You must be signed in to change notification settings - Fork 2
/
euler.py
2698 lines (2121 loc) · 74.9 KB
/
euler.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python3
# vim: set tabstop=4 shiftwidth=4 expandtab :
# Generated by letscode
"""Project Euler solutions"""
import string
import math
import itertools
import collections
import heapq
from prime import prime_factors_list, sieve, nb_divisors, yield_primes
from prime import primes_up_to, nb_prime_divisors, totient, divisors_sieve
from prime import is_prime, prime_divisors_sieve, mult
from functions import ceil, gcd, modinv
from functions import fibo, lcmm, yield_pythagorean_triples_of_peri
from functions import Tn, Pn, Hn, isPn, champernowne_digit
from poker import Hand
import os
from timeit import default_timer as timer
resource_folder = ''
def euler1(lim=1000):
"""Solution for problem 1."""
# could use sum formula here
return sum(i for i in range(lim) if i % 3 == 0 or i % 5 == 0)
def euler2(lim=4000000):
"""Solution for problem 2."""
s = 0
for f in fibo(1, 2):
if f > lim:
return s
if f % 2 == 0:
s += f
def euler3(n=600851475143):
"""Solution for problem 3."""
return prime_factors_list(n)[-1]
def euler4(l=3):
"""Solution for problem 4."""
# simple optimisation would be an early break
return max(n for n in (i * j for i, j in itertools.combinations(range(10 ** (l - 1), 10 ** l), 2)) if str(n) == str(n)[::-1])
def euler5(lim=20):
"""Solution for problem 5."""
return lcmm(*range(1, lim + 1))
def euler6(lim=100):
"""Solution for problem 6."""
# could use sum formula here
numbers = range(1, lim + 1)
sum_ = sum(numbers)
return sum_ * sum_ - sum(i * i for i in numbers)
def nth(iterable, n, default=None):
"""Returns the nth item or a default value.
From http://stackoverflow.com/questions/12007820/better-ways-to-get-nth-element-from-an-unsubscriptable-iterable ."""
return next(itertools.islice(iterable, n, None), default)
def euler7(n=10001):
"""Solution for problem 7."""
return nth(yield_primes(), n - 1)
def euler8(l=13):
"""Solution for problem 8."""
# Too lazy for optimisations
n = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
return max(mult(int(c) for c in s) for s in (n[i:i + l] for i in range(len(n))))
def euler9(p=1000):
"""Solution for problem 9."""
for a, b, c in yield_pythagorean_triples_of_peri(p):
return a * b * c
def euler10(lim=2000000):
"""Solution for problem 10."""
return sum(primes_up_to(lim))
def euler11_():
"""Solution for problem 11."""
pass
def euler12(nb_div=500):
"""Solution for problem 12."""
# T(n) = n(n+1)/2
# T(2k + 0) = 2k*(2k+1) / 2 = k*(2k+1)
# and gcd(k, 2*k+1) = gcd(k, 1) = 1
# Thus, nb_div(T(2k)) = nb_div(k) * nb_div(2k+1)
# T(2k + 1) = (2k+1)*(2k+2) / 2 = (2k+1)(k+1)
# and gcd(2k+1, k+1) = gcd(k, k+1) = gcd(k, 1) = 1
# Thus, nb_div(T(2k + 1)) = nb_div(k+1) * nb_div(2k+1)
nb_div_k, nb_div_kp1 = None, 1
for k in itertools.count(1):
nb_div_k, nb_div_kp1 = nb_div_kp1, nb_divisors(k + 1)
c = 2 * k + 1
nb_div_c = nb_divisors(c)
if nb_div_k * nb_div_c >= nb_div:
return c * k
if nb_div_kp1 * nb_div_c >= nb_div:
return c * (k + 1)
def euler13_():
"""Solution for problem 13."""
pass
def euler14(lim=1000000):
"""Solution for problem 14."""
collatz = {1: 1}
for i in range(2, lim):
if i not in collatz:
chain = []
while i not in collatz:
chain.append(i)
i = (3 * i + 1) if i % 2 else (i // 2)
stop = collatz[i] + 1
for idx, val in enumerate(reversed(chain)):
collatz[val] = stop + idx
assert i in collatz
return max((v, k) for k, v in collatz.items() if k <= lim)[1]
def euler15(col=20, row=20):
"""Solution for problem 15."""
nb_routes = [[0] * (row + 1) for i in range(col + 1)]
nb_routes[0][0] = 1
for i in range(col + 1):
for j in range(row + 1):
if i:
nb_routes[i][j] += nb_routes[i - 1][j]
if j:
nb_routes[i][j] += nb_routes[i][j - 1]
return nb_routes[-1][-1]
def sum_digit(n):
return sum(int(c) for c in str(n))
def euler16(n=1000):
"""Solution for problem 16."""
return sum_digit(2 ** n)
def euler17(lim=1000):
"""Solution for problem 17."""
# Optimisation could be done by grouping similar number
# prefixes/suffixes and use multiplications instead of
# repeated sums but this is fast enough
small_numbers_str = {
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"
}
ten_multiples_str = {
2: "twenty", 3: "thirty", 4: "forty", 5: "fifty",
6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"
}
small_numbers_len = {k: len(v) for k, v in small_numbers_str.items()}
ten_multiples_len = {k: len(v) for k, v in ten_multiples_str.items()}
and_len = len("and")
hundred_len = len("hundred")
thousand_len = len("thousand")
def get_len_for_number(n):
n, units = divmod(n, 10)
n, tens = divmod(n, 10)
thousands, hundreds = divmod(n, 10)
total = 0
if thousands:
total += small_numbers_len[thousands] + thousand_len
if hundreds:
total += small_numbers_len[hundreds] + hundred_len
if tens or units:
total += and_len
if tens > 1:
total += ten_multiples_len[tens]
else:
units += 10 * tens # move tens in units
if units:
total += small_numbers_len[units]
return total
return sum(get_len_for_number(i) for i in range(1, lim + 1))
def euler18_():
"""Solution for problem 18."""
pass
def euler19():
"""Solution for problem 19."""
day = 2 # Tuesday 1 Jan 1901
nb_days = 7
freq = [0] * nb_days
months = [nb % nb_days for nb in (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)]
for year in range(1901, 2001):
for i, month in enumerate(months):
freq[day] += 1
day = (day + month + (1 if (i == 1 and (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))) else 0)) % nb_days
return freq[0]
def euler20(n=100):
"""Solution for problem 20."""
return sum_digit(math.factorial(n))
def euler21(lim=10000):
"""Solution for problem 21."""
sum_div = [sum(l) for l in divisors_sieve(lim)]
return sum(
s + i
for i, s in enumerate(sum_div)
if s < i and sum_div[s] == i)
def euler22(f='p022_names.txt'):
"""Solution for problem 22."""
with open(os.path.join(resource_folder, f)) as file_:
return sum((i + 1) * sum(1 + ord(c) - ord('A') for c in name)
for i, name in enumerate(sorted(''.join(file_.readlines()).replace('"', '').split(','))))
def euler23(lim=28123):
"""Solution for problem 23."""
abun = [i > 0 and sum(l) > i for i, l in enumerate(divisors_sieve(lim))]
return sum(
n for n in range(lim)
if not any(i for i in range(1 + n // 2) if abun[i] and abun[n - i]))
def euler24():
"""Solution for problem 24."""
return int(''.join(nth(itertools.permutations(string.digits), 1000000 - 1)))
def euler25(nb_digits=1000):
"""Solution for problem 25."""
lim = 10 ** (nb_digits - 1)
for i, f in enumerate(fibo()):
if f > lim:
return 1 + i
def length_recur_cycle(a, b, base=10):
remainders = {}
for i in itertools.count():
if a == 0:
return 0
if a in remainders:
return i - remainders[a]
remainders[a] = i
a = (a * base) % b
def euler26(lim=1000):
"""Solution for problem 26."""
return max(range(2, lim), key=lambda i: length_recur_cycle(1, i))
def euler27(lim=1000):
"""Solution for problem 27."""
# P(0) = b must be prime
# P(1) = 1 + a + b must be prime so 1+a+b >= 2 => a => 1-b
maxa, maxb, maxn = None, None, 0
for b in primes_up_to(lim):
for a in range(1 - b, lim + 1):
assert -lim <= a <= lim
n = 0
while is_prime(n * n + a * n + b):
n += 1
if n > maxn:
maxa, maxb, maxn = a, b, n
return maxa * maxb
def euler28(n=1001):
"""Solution for problem 28."""
# For a level of size s (s>1), corners are :
# s*s, s*s-s+1, s*s-2s+2, s*s-3s+3
# Their sum is 4*s*s - 6*s + 6 (3 <= s <= n)
# Writing s = 2*j + 3, sum of corners is
# 16*j*j + 36j + 24
# This sum could be computed in constant time but this is
# fast enough.
return 1 + sum(16 * j * j + 36 * j + 24 for j in range(n // 2))
def euler29(lima=100, limb=100):
"""Solution for problem 29."""
n = set()
for a in range(2, lima + 1):
p = a
for _ in range(2, limb + 1):
p *= a
n.add(p)
return len(n)
def euler30():
"""Solution for problem 30."""
# sum(fifth(digits)) = n
# nb_digits * fifth(0) < sum(fifth(digits)) <= nb_digits * fifth(base - 1)
# base ^ (nb_digits - 1) <= n < base ^ nb_digits
# => base ^ (nb_digits - 1) <= nb_digits * fifth(base - 1)
# with base = 10, nb_digits <= 6
fifth = {c: int(c) ** 5 for c in string.digits}
dict_sum = {}
for nb_dig in range(2, 6 + 1):
for l in itertools.combinations_with_replacement('123456789', nb_dig):
dict_sum.setdefault(sum(fifth[c] for c in l), []).append(list(l))
return sum(n for n, l in dict_sum.items() if [c for c in sorted(str(n)) if c != '0'] in l)
def euler31(obj=200, coins=None):
"""Solution for problem 31."""
if coins is None:
coins = [1, 2, 5, 10, 20, 50, 100, 200]
nb_ways = [1] + [0] * obj
for c in coins:
for v in range(obj + 1 - c):
nb_ways[v + c] += nb_ways[v]
return nb_ways[-1]
def euler32():
"""Solution for problem 32."""
# nb_dig(a*b) = nb_dig(a) + nb_dig(b) or nb_dig(a) + nb_dig(b) - 1
# we want : a * b = c with 0 < a < b < c
# and we must have : nb_dig(a) + nb_dig(b) + nb_dig(c) = 9
# i + j + k = 9 and (i + j = k or i + j - 1 = k)
# => 2i + 2j = 9 (impossible) or 2i + 2j = 10
# => i + j = 10 => (1, 4, 4), (2, 3, 4).
return sum({a * b
for a in range(2, 98)
for b in range(1234 if a <= 10 else 123, 10000 // a + 1)
if ''.join(sorted(list(str(a) + str(b) + str(a * b)))) == '123456789'
})
def euler33():
"""Solution for problem 33."""
# Different options reducing to b/c (with 0 < b < c < 10 and 0 <= a < 10) are :
# ab / ac (possible only if a=0 or b=c : not interesting)
# ba / ca (possible only if a=0 or b=c : not interesting)
# ab / ca (possible iif 9bc = a (10c - b))
# ba / ac (possible iif 9bc = a (10b - c))
# Also, top / bottom = b/c <=> top * c = bottom * b
t, b = [mult(lst)
for lst in zip(*[(b, c)
for b, c in itertools.combinations(range(1, 10), 2)
for a in range(1, 10)
for top, bot in [(10 * a + b, 10 * c + a), (10 * b + a, 10 * a + c)]
if top * c == bot * b])]
return b // gcd(t, b)
def euler34():
"""Solution for problem 34."""
# sum(fact(digits)) = n
# nb_digits * fact(0) < sum(fact(digits)) <= nb_digits * fact(base - 1)
# base ^ (nb_digits - 1) <= n < base ^ nb_digits
# => base ^ (nb_digits - 1) <= nb_digits * fact(base - 1)
# with base = 10, we have nb_digits <= 7
fact = {c: math.factorial(int(c)) for c in string.digits}
dict_sum = {}
for nb_dig in range(2, 7 + 1):
for l in itertools.combinations_with_replacement(string.digits, nb_dig):
dict_sum.setdefault(sum(fact[c] for c in l), []).append(list(l))
return sum(n for n, l in dict_sum.items() if sorted(str(n)) in l)
def euler35(nb_dig_max=6):
# permutations of 2 digits or more must contain only 1, 3, 7, 9
count = 4 # counting 2, 3, 5 and 7
final_numbers = {'1', '3', '7', '9'}
for l in range(2, nb_dig_max + 1):
for p in itertools.product(final_numbers, repeat=l):
p_int = int(''.join(p))
perm = {int(''.join(p[i:] + p[:i])) for i in range(len(p))}
if p_int == min(perm) and all(is_prime(n) for n in perm):
count += len(perm)
return count
def euler36():
"""Solution for problem 36."""
# 999999
sol = []
for i in range(1000):
s = str(i)
for beg in (-1, -2):
n = int(s + s[beg::-1])
s2 = bin(n)[2:]
if s2 == s2[::-1]:
sol.append(n)
return sum(sol)
def euler37():
"""Solution for problem 37."""
left, sol = {0}, []
while left:
left = {n for n in (10 * l + i for i in range(10) for l in left) if is_prime(n)}
sol.extend(n for n in left if n > 10 and all(is_prime(n % (10 ** pow)) for pow in range(1, len(str(n)))))
return sum(sol)
def euler38():
"""Solution for problem 38."""
# '123456789' will be decomposed in at least two elements,
# the smallest being 4 at most characters long
sol = 0
digits = {str(d) for d in range(1, 10)}
for n in range(10000):
s = ""
for i in itertools.count(1):
s += str(n * i)
if len(s) >= len(digits):
if len(s) == len(digits) and set(s) == digits:
sol = max(sol, int(s))
break
return sol
def euler39(lim=1000):
"""Solution for problem 39."""
return max(range(1, lim + 1), key=lambda p: len(list(yield_pythagorean_triples_of_peri(p))))
def euler40():
"""Solution for problem 40."""
return mult(champernowne_digit(pow(10, i) - 1) for i in range(6))
def euler41():
"""Solution for problem 41."""
# sum(i, i=1..n) is is not divisible by 3 only if n = 1, 4, 7 or bigger than 9
for nb_dig in (7, 4, 1):
for l in itertools.permutations(str(d) for d in range(nb_dig, 0, -1)):
n = int(''.join(l))
if is_prime(n):
return n
def euler42_():
"""Solution for problem 42."""
pass
def euler43():
"""Solution for problem 43."""
# Could be optimised by using a constructive solution starting from the end
div = [(17, 7), (13, 6), (11, 5), (7, 4), (5, 3), (3, 2), (2, 1)]
return sum(int(''.join(p))
for p in itertools.permutations(string.digits)
if all(int(''.join(p[i:i + 3])) % d == 0 for d, i in div))
def euler44():
"""Solution for problem 44."""
# We look for minimal value of P(m) = P(k) - P(j)
# Such that P(k) + P(j) is pentagonal.
# We must have j < m < k.
for m in itertools.count():
pm = Pn(m)
for j in range(1, m):
pj = Pn(j)
pk = pm + pj
if isPn(pk) and isPn(pj + pk):
return pm
def euler45(nb_fact=4):
"""Solution for problem 45."""
t_gen = (Tn(n) for n in itertools.count())
p_gen = (Pn(n) for n in itertools.count())
h_gen = (Hn(n) for n in itertools.count())
t, p, h = next(t_gen), next(p_gen), next(h_gen)
while True:
if p > t:
t = next(t_gen)
elif t > p or h > p:
p = next(p_gen)
elif p > h:
h = next(h_gen)
elif t in [0, 1, 40755]:
t, p, h = next(t_gen), next(p_gen), next(h_gen)
else:
return t
def euler46():
"""Solution for problem 46."""
for i in itertools.count(9, 2):
if not is_prime(i) and not any(is_prime(i - 2 * n * n) for n in range(1, ceil(math.sqrt(i // 2)))):
return i
def euler47(nb_fact=4):
"""Solution for problem 47."""
cand = []
for i in itertools.count(2):
if nb_prime_divisors(i) == nb_fact:
cand.append(i)
if len(cand) == nb_fact:
return cand[0]
else:
cand = []
def euler48(n=1000, nb_dig=10):
"""Solution for problem 48."""
mod = 10 ** nb_dig
return sum(pow(i, i, mod) for i in range(1, n + 1)) % mod
def sorted_number(n):
# Reversed to keep 0 instead of` discarding them
return int(''.join(sorted(str(n), reverse=True)))
def euler49(nb_digit=4):
"""Solution for problem 49."""
low = 10 ** (nb_digit - 1)
high = 10 ** nb_digit - 1
prime = sieve(high)
prime_perm = {}
for i in range(low, high + 1):
if prime[i]:
prime_perm.setdefault(sorted_number(i), []).append(i)
for perms in prime_perm.values():
# could iterate only on a,b but not a bottleneck
for a, b, c in itertools.combinations(perms, 3):
assert c > b > a
if b - a == c - b and a != 1487:
return int(str(a) + str(b) + str(c))
def euler50(lim=1000000):
"""Solution for problem 50."""
primes = sieve(lim)
list_primes = [i for i, p in enumerate(primes) if p]
max_len, max_sum = 0, 0
for i in range(len(list_primes)):
for j in range(i + max_len + 1, len(list_primes)):
s = sum(list_primes[i:j]) # could use sum array here
if s > lim:
break
elif primes[s]:
assert j - i > max_len
max_len, max_sum = j - i, s
return max_sum
def euler51(nb=8):
"""Solution for problem 51."""
# Iterating on batches of number of same length to be able to use a sieve.
# For each prime, looking for digits one can change, then the possible
# combinations of these digits. For each combination, we compute the value
# of the corresponding mask and check primality.
base = 10 # Not so much of a variable due to various optimisations
lim = 1 + base - nb # replaced digit must be smaller than lim
# optimisation : precomputing powers of 10
pows = []
# optimisation : the mask (and so its length) must be divisible by 3 for
# big families, otherwise, we'd have too many multiple of 3.
len_mask_step = 3 if nb >= 8 else 1
# optimisation : last number can't be changed for families of 4 or more
last_nb_can_chg = nb <= 4
low = 1
while True:
high = base * low
primes = sieve(high)
pows.append(low)
for n in range(low, high):
if primes[n]:
n_str = [int(c) for c in reversed(str(n))]
for val_replaced in range(lim):
pos = [i for i, c in enumerate(n_str)
if c == val_replaced and (i or last_nb_can_chg)]
for len_mask in range(len_mask_step, 1 + len(pos), len_mask_step):
for pos_mask in itertools.combinations(pos, len_mask):
val_mask = sum(pows[i] for i in pos_mask)
if 1 + sum(1 for i in range(1, base - val_replaced) if primes[n + i * val_mask]) >= nb:
return n
low = high
def euler52(lim=6):
"""Solution for problem 52."""
for x in itertools.count(1):
digits = sorted_number(x)
if all(digits == sorted_number(i * x) for i in range(2, lim + 1)):
return x
def euler53(n_max=100, lim=1000000):
"""Solution for problem 53."""
# C(n, r) = n! / (r! (n-r)!) for r <= n
# = prod(n + 1 - i / i, i =1..r)
def C(n, r):
r = min(r, n - r) # symmetry
return mult(n - i for i in range(r)) // mult(i + 1 for i in range(r))
s = 0
for n in range(n_max + 1):
for r in range(n // 2 + 1): # stop halfway - use symmetry
if C(n, r) > lim:
s += 1 if 2 * r == n else 2
return s
def euler54(f='p054_poker.txt'):
"""Solution for problem 54."""
ret = 0
with open(os.path.join(resource_folder, f)) as file_:
for l in file_:
hand1, hand2 = Hand.from_string(l)
ret += hand1 > hand2
return ret
def euler55_():
"""Solution for problem 55."""
pass
def euler56(lim=100):
"""Solution for problem 56."""
int_ = {str(d): d for d in range(10)}
maxi = 1
for a in range(2, lim + 1):
p = a
for b in range(2, lim + 1):
p *= a
maxi = max(maxi, sum(int_[d] for d in str(p)))
return maxi
def euler57(nb_exp=1000):
"""Solution for problem 57."""
# If expansion at level n is a/b
# analysis shows that at level n+1, we have:
# (2*b+a) / (a+b)
# Also, gcd(2*b+a, a+b) = gcd(b, a+b) = gcd(a, b)
# Thus, gcd is conserved : if we start with a reduced
# fraction, all fractions will be reduced
nb = 0
a = b = 1
for i in range(nb_exp + 1):
assert gcd(a, b) == 1
if len(str(a)) > len(str(b)):
nb += 1
a, b = 2 * b + a, a + b
return nb
def euler58(ratio=0.1):
"""Solution for problem 58."""
# First analysis in euler28
# Corners are s*s-3s+3, s*s-2s+2, s*s-s+1, s*s
# s*s is likely not to be prime
nb_prime = 0
for s in itertools.count(3, 2):
for i in range(1, 4):
if is_prime(s * s - i * s + i):
nb_prime += 1
if nb_prime < ratio * (2 * s - 1):
return s
def euler59_():
"""Solution for problem 59."""
pass
def euler60_():
"""Solution for problem 60."""
# awful C solution on PE https://projecteuler.net/thread=60;page=3#20807
pass
def euler61_():
"""Solution for problem 61."""
pass
def euler62(nb_perm=5):
"""Solution for problem 62."""
cube_perm, l = {}, None
for i in itertools.count():
c = i * i * i
new_l = len(str(c))
if l != new_l:
cand = [numbers[0]
for c, numbers in cube_perm.items() if len(numbers) == nb_perm]
if cand:
return min(cand) ** 3
cube_perm, l = {}, new_l
cube_perm.setdefault(sorted_number(c), []).append(i)
def euler63():
"""Solution for problem 63."""
# 10^(n-1) <= x^n < 10^n
# (n-1) * log(10) <= n * log(x) < n * log(10)
# (n-1) * log(10) / n <= log(x) < log(10)
# exp((n-1) * log(10) / n) <= x < 10
# and LHS becomes bigger than 9 at n = 22
return sum(
10 - ceil(math.exp((n - 1) * math.log(10) / n))
for n in range(1, 22))
def euler64_():
"""Solution for problem 64."""
pass
def euler65_():
"""Solution for problem 65."""
pass
def euler66_():
"""Solution for problem 66."""
# http://en.wikipedia.org/wiki/Pell's_equation
pass
def euler67_():
"""Solution for problem 67."""
pass
def euler68_():
"""Solution for problem 68."""
# awful C solution on PE https://projecteuler.net/thread=68;page=3#21386
pass
def euler69(lim=1000000):
"""Solution for problem 69."""
return max((float(i) / t, i) for i, t in enumerate(totient(lim)) if i)[1]
def euler70(lim=10000000):
"""Solution for problem 70."""
n, val = lim, lim
for i, t in enumerate(totient(lim)):
if i > 1:
new_val = float(i) / t
if new_val < val and sorted_number(i) == sorted_number(t):
n, val = i, new_val
return n
def euler71_():
"""Solution for problem 71."""
pass
def euler72(lim=1000000):
"""Solution for problem 72."""
return sum(totient(lim))
def euler73_():
"""Solution for problem 73."""
pass
def euler74_():
"""Solution for problem 74."""
pass
def euler75(lim=1500000):
"""Solution for problem 75."""
# http://en.wikipedia.org/wiki/Pythagorean_triple
# a = (m*m-n*n)*d
# b = 2*m*n*d
# c = (m*m+n*n)*d
# p = 2*m*(m+n)*d
# with : pgcd(m,n)=1 and m < n < 2*m.
diff_c = [0] * (1 + lim) # 0: no solution / -1: more than 1 solution
for m in range(1 + int(math.sqrt(lim / 2))):
m2 = m * m
for k in range(m + 1, 2 * m): # k = n + m
if gcd(m, k) == 1:
n = k - m
n2 = n * n
mk2 = 2 * m * k
for d in range(1, 1 + lim // mk2):
p = mk2 * d
c = (m2 + n2) * d
old_res = diff_c[p]
if old_res == 0:
diff_c[p] = c
elif old_res != c:
diff_c[p] = -1
return sum(1 for d in diff_c if d > 0)
def euler76_():
"""Solution for problem 76."""
pass
def euler77_():
"""Solution for problem 77."""
pass
def euler78_():
"""Solution for problem 78."""
pass
def euler79_():
"""Solution for problem 79."""
pass
def euler80_():
"""Solution for problem 80."""
pass
def euler81_():
"""Solution for problem 81."""
pass
def euler82_():
"""Solution for problem 82."""
pass
def euler83_():
"""Solution for problem 83."""
pass
def euler84_():
"""Solution for problem 84."""
pass
def euler85(target=2000000):
"""Solution for problem 85."""
# nb_rect(i, 1) = 1 (of size i) + 2 (of size i-1) + ... + i (of size 1) = i*(i+1)/2
# nb_rect(i, j) = nb_rect(i, 1) (of height j) + 2 * nb_rect(i, 1) (of height j-1) + ... + j * nb_rect(i, 1) (of height 1)
# = nb_rect(i, 1) * nb_rect(j, 1) = i*(i+1)*j*(j+1)/4
# Solutions to nb_rect(i, j) = t for a given i are, with delta = 1 + 16 t / [i * (i+1)]
# j1 = (-1 - sqrt(delta))/2 < 0 and j2 = (-1 + sqrt(delta))/2 > 0
# Best approximations are ceil and floor of j2.
sol_dist, sol_area = target, 0
for i in itertools.count(1):
tmp_i = i * (i + 1)
delta = 1 + target * 16 / tmp_i
j2 = (-1 + math.sqrt(delta)) / 2
js = set([math.floor(j2), math.ceil(j2)])
for j in js:
val = tmp_i * j * (j + 1) / 4
dist = math.fabs(target - val)
if dist < sol_dist:
sol_dist, sol_area = dist, i * j
if i > max(js):
return sol_area
def euler86_():
"""Solution for problem 86."""
pass
def euler87(lim=50000000):
"""Solution for problem 87."""
# the biggest prime needed p is such that
# lim >= p**2 + 2**3 + 2**4
# p <= sqrt(lim - 24)
primes = list(primes_up_to(int(math.sqrt(lim - 24))))
sol = set()
for a in primes:
sum_a = a ** 4
if sum_a > lim:
break
for b in primes:
sum_b = sum_a + b ** 3
if sum_b > lim:
break
for c in primes:
sum_c = sum_b + c ** 2
if sum_c > lim:
break
sol.add(sum_c)
return len(sol)
def euler88_():
"""Solution for problem 88."""
pass
def euler89_():
"""Solution for problem 89."""
pass
def euler90():
"""Solution for problem 90."""
base = 10
nb_face = 6
def substitute(n):
assert 0 <= n < base
return 6 if n == 9 else n
# The values we want to display with 9 replaced by 6
squares = [tuple(substitute(n) for n in divmod(i * i, base)) for i in range(1, base)]
# Possible dice arrangements with 9 replaced by 6 to make the logic easier
permutations = (set(substitute(n) for n in p)
for p in itertools.combinations(range(base), nb_face))
# Filtering arrangements as an optimisation
candidates = (p for p in permutations
if all((a in p or b in p) for a, b in squares))
# Counting the matching arrangements
return sum(1 for (c1, c2) in itertools.combinations(candidates, 2)
if all(((a in c1 and b in c2) or (b in c1 and a in c2)) for a, b in squares))
def euler91_bruteforce(size=50):
"""Solution for problem 91.
Bruteforce is fast enough to get a solution."""
i = 0
for p1, q1, p2, q2 in itertools.product(range(size + 1), repeat=4):
if (p1, p2) < (q1, q2): # not to count them twice
low, med, high = sorted(x ** 2 + y ** 2 for x, y in [(p1, p2), (q1, q2), (p1 - q1, p2 - q2)])
if low and low + med == high:
i += 1
return i
def euler91(size=50):
"""Solution for problem 91."""
# We have 2 kinds of right angles :
# - angle in 0 (hypothenus is PQ) : size*size of them
# - without any loss of generality, angle in P (p1, p2):
# OP is the hypothenus and with H (h1, h2) middle of OP, we have :
# |OP| = 2*|OH| = 2*|HP| = 2*|HQ|
# p1^2 + p2^2 = 4 * ((q1-h1)^2 + (q2-h2)^2)
# = (2*q1 - p1)^2 + (2*q2 - p2)^2
# - If Q is on axis : 2*size*size obvious solutions
# - If Q is not on axis, we solve for all p1,p2,q1.
# A few optimisations :
# - we can assume p1 >= p2 and count solution twice if relevant
# - when looking for q1, we can stop early (h1 + |OH|)
i = 3 * size * size
for p1, p2 in itertools.combinations_with_replacement(range(size + 1), 2):
dp = p1 ** 2 + p2 ** 2
if dp:
for q1 in range(1, min(size, int((p1 + math.sqrt(dp)) / 2)) + 1):
square = dp - (2 * q1 - p1) ** 2
if square >= 0:
root = int(math.sqrt(square))
if root * root == square:
assert p2 % 2 == root % 2
for s in set([-root, +root]):
q2 = (p2 + s) // 2
if 1 <= q2 <= size and (q1, q2) != (p1, p2):
i += 1 if p1 == p2 else 2
return i
def euler92_():
"""Solution for problem 92."""
pass