Rebased projecteuler folder, now includes all contest programming stuff

This commit is contained in:
2021-10-26 10:54:24 +02:00
parent 1aa6120838
commit e0c627a384
77 changed files with 203 additions and 67 deletions

18
projecteuler/001/main.py Normal file
View File

@@ -0,0 +1,18 @@
import os
# Find the sum of all number that are divisible by either 3 or 5 below 1000
threes = set()
fives = set()
for x in range(334):
threes.add(3*x)
for x in range(200):
fives.add(5*x)
threesfives = threes.union(fives)
print(sum(threesfives))

21
projecteuler/002/main.py Normal file
View File

@@ -0,0 +1,21 @@
import os
# Find the sum of all Fibonacci numbers below four million
s = 0
n = 1
m = 1
while m < 4000000:
temp = m
m = n + temp
n = temp
if m % 2 == 0:
s = s + m
print(s)

55
projecteuler/003/main.py Normal file
View File

@@ -0,0 +1,55 @@
import os
import numpy as np
# Find the largest prime factor of 600851475143
def isDivisible(n, ms):
res = False
for m in ms:
if n % m == 0:
res = True
break
return res
def getNextPrime(ps):
if len(ps) == 0:
return [2]
else:
p = ps[-1] + 1
while isDivisible(p, [q for q in ps if q <= np.sqrt(p)]):
p = p + 1
ps.append(p)
return ps
def findFactors(n):
ps = [2]
res = []
rest = n
stop = np.sqrt(n)
while rest != 1:
if rest % ps[-1] == 0:
res.append(ps[-1])
rest = rest / ps[-1]
else:
ps = getNextPrime(ps)
if stop < ps[-1]:
break
return res
def main():
print("Hello, this is Patrick")
number = 600851475143
fs = findFactors(number)
print(max(fs))
if __name__ == "__main__":
main()

62
projecteuler/004/main.py Normal file
View File

@@ -0,0 +1,62 @@
import os
import numpy
# Find the largest palindrome made from the product of two 3-digit numbers
def reverse(s):
return s[::-1]
def getPalins(n):
res = [0]
m = 1
while len(str(m)) <= n:
s = str(m)
if s == reverse(s):
res.append(m)
m = m + 1
return res
def checkPalin(n):
s = str(n)
return s == reverse(s)
def getProducts(lower, upper):
res = []
for i in range(lower, upper + 1):
for j in range(lower, upper + 1):
res.append(i*j)
return res
def main():
testtext = "Hello, this is Patrick"
print(testtext)
# palins = getPalins(6)
# print(palins)
prods = getProducts(100, 999)
palinprods = list(filter(lambda x: checkPalin(x), prods))
print(max(palinprods))
if __name__ == "__main__":
main()

38
projecteuler/005/main.py Normal file
View File

@@ -0,0 +1,38 @@
import os
import numpy
# Find the smallest number that is divisible by all numbers from 1 to 20
def isDivisible(n, ms):
res = True
for m in ms:
if n % m != 0:
res = False
break
return res
def findSmallestDivBy(ns):
res = 1
while not isDivisible(res, ns):
res = res + 1
return res
def main():
print("Hello, this is Patrick")
x = findSmallestDivBy([2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19])
print(x)
if __name__ == "__main__":
main()

39
projecteuler/006/main.py Normal file
View File

@@ -0,0 +1,39 @@
import os
import numpy
def sumSquare(n):
res = 0
for i in range(n+1):
res = res + pow(i, 2)
return res
def squareSum(n):
return pow(sum(range(n+1)), 2)
def main():
print("Hello, this is Patrick")
# s1 = sumSquare(10)
# s2 = squareSum(10)
# print(s1, s2)
print(abs(sumSquare(100) - squareSum(100)))
if __name__ == "__main__":
main()

54
projecteuler/007/main.py Normal file
View File

@@ -0,0 +1,54 @@
import os
import numpy as np
# Find the 10001st prime number
def isDivisible(n, ms):
res = False
for m in ms:
if n % m == 0:
res = True
break
return res
def getNextPrime(ps):
if len(ps) == 0:
return [2]
else:
p = ps[-1] + 1
while isDivisible(p, [q for q in ps if q <= np.sqrt(p)]):
p = p + 1
ps.append(p)
return ps
def findNthPrime(n):
ps = [2]
i = 1
while n > i:
ps = getNextPrime(ps)
i = i + 1
print(i, ps[-1])
return ps[-1]
def main():
print("Hello, this is Patrick")
p = findNthPrime(10001)
print(p)
if __name__ == "__main__":
main()

79
projecteuler/008/main.py Normal file
View File

@@ -0,0 +1,79 @@
import os
import numpy as np
# Calculate the highest value of the product of 13 consecutive numbers of the following sequence:
# 73167176531330624919225119674426574742355349194934
# 96983520312774506326239578318016984801869478851843
# 85861560789112949495459501737958331952853208805511
# 12540698747158523863050715693290963295227443043557
# 66896648950445244523161731856403098711121722383113
# 62229893423380308135336276614282806444486645238749
# 30358907296290491560440772390713810515859307960866
# 70172427121883998797908792274921901699720888093776
# 65727333001053367881220235421809751254540594752243
# 52584907711670556013604839586446706324415722155397
# 53697817977846174064955149290862569321978468622482
# 83972241375657056057490261407972968652414535100474
# 82166370484403199890008895243450658541227588666881
# 16427171479924442928230863465674813919123162824586
# 17866458359124566529476545682848912883142607690042
# 24219022671055626321111109370544217506941658960408
# 07198403850962455444362981230987879927244284909188
# 84580156166097919133875499200524063689912560717606
# 05886116467109405077541002256983155200055935729725
# 71636269561882670428252483600823257530420752963450
def product(xs):
res = 1
for x in xs:
res = res * x
return res
def main():
print("Hello, this is Patrick")
s = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""
s = ''.join(s.split())
# print(s)
ps = []
for i in range(len(s) - 13):
ps.append(product([int(x) for x in s[i:i+13]]))
print(max(ps))
if __name__ == "__main__":
main()

28
projecteuler/009/main.py Normal file
View File

@@ -0,0 +1,28 @@
import os
import numpy as np
# Find the pythagorean triplet that sums to 1000
def checkPythTriplet(a, b, c):
return pow(a, 2) + pow(b, 2) == pow(c, 2)
def main():
print("Hello, this is Patrick")
for b in range(500):
for a in range(b):
c = 1000 - b - a
if b < c and checkPythTriplet(a, b, c):
print(a, b, c, a*b*c)
if __name__ == "__main__":
main()

84
projecteuler/010/main.py Normal file
View File

@@ -0,0 +1,84 @@
import os
import math
import numpy as np
# Find the sum of all prime numbers below two million
def isDivisible(n, ms):
res = False
for m in ms:
if n % m == 0:
res = True
break
return res
def getNextPrime(ps):
if len(ps) == 0:
return [2]
else:
p = ps[-1] + 1
while isDivisible(p, [q for q in ps if q <= np.sqrt(p)]):
p = p + 1
ps.append(p)
return ps
def getFirstNPrimesBad(n):
assert n >= 0
l = 0
ps = []
while l < n:
ps = getNextPrime(ps)
l = l + 1
return ps
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def product(xs):
res = 1
for x in xs:
res = res * x
return res
# Found a formula for this exact question:
# https://oeis.org/A007504
# a(n) = (n^2/2)*(log n + log log n - 3/2 + (log log n - 3)/log n + (2 (log log n)^2 - 14 log log n + 27)/(4 log^2 n) + O((log log n/log n)^3))
# def getSumOfPrimes(n):
# return 0.5 * pow(n, 2) * (np.log(n) + np.log(np.log(n)) - 1.5 + (np.log(np.log(n)) - 3) / np.log(n) +
# (2 * pow(np.log(np.log(n)), 2) - 14 * np.log(np.log(n)) + 27) / (4 * np.log2(n)) + some O term)
# Unusable because of the o term, unfortunately. Also, I don't know exactly for which n prime numbers I want to calculate this sum.
# We will have to do it the hard way
def main():
print("Hello, this is Patrick")
ps = sieve(2000000)
print(sum(ps))
if __name__ == "__main__":
main()

97
projecteuler/011/main.py Normal file
View File

@@ -0,0 +1,97 @@
import os
import math
import numpy as np
# Find the highest product of four adjacent numbers in the following grid
# 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
def product(xs):
res = 1
for x in xs:
res = res * x
return res
def main():
print("Hello, this is Patrick")
ss = """
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
"""
nss = list(map(lambda s: s.split(" "), ss.strip().split("\n")))
xss = []
for ns in nss:
xs = []
for n in ns:
xs.append(int(n))
xss.append(xs)
ps = []
for xs in range(len(xss)):
for x in range(len(xss[xs])):
if xs < len(xss) - 3:
p = [xss[xs + a][x] for a in range(4)]
ps.append(product(p))
if x < len(xss[xs]) - 3:
p = xss[xs][x : x + 4]
ps.append(product(p))
if xs < len(xss) - 3 and x < len(xss[xs]) - 3:
p = [xss[xs + a][x + a] for a in range(4)]
ps.append(product(p))
if xs > 2 and x < len(xss[xs]) - 3:
p = [xss[xs - a][x + a] for a in range(4)]
ps.append(product(p))
print(max(ps))
if __name__ == "__main__":
main()

39
projecteuler/012/main.py Normal file
View File

@@ -0,0 +1,39 @@
import os
import math
import numpy as np
# Triangle numbers are simply the sum of all natural numbers.
# Then, find the first triangle number that has over five hundred divisors.
def getTriangle(n):
# return sum(range(1, n + 1))
# Instead just use the formula like any normal human being
return int(n * (n+1) / 2)
def getTriangles(n):
return [getTriangle(x) for x in range(1, n + 1)]
def getNumberOfDivs(n):
# Fuck this function
def main():
print("Hello, this is Patrick")
ts = getTriangles(7)
print(ts)
for t in ts:
print(getNumberOfDivs(t))
if __name__ == "__main__":
main()

138
projecteuler/013/main.py Normal file
View File

@@ -0,0 +1,138 @@
import os
import math
import numpy as np
# Work out the first 10 digits of the sum of 100 50-digit numbers
s = '''
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
'''
def main():
print("Hello, this is Patrick")
ns = list(map(lambda x: int(x), s.strip().split('\n')))
print(sum(ns))
if __name__ == "__main__":
main()

64
projecteuler/014/main.py Normal file
View File

@@ -0,0 +1,64 @@
import os
import math
import numpy as np
# Given the following sequence, find the longest chain that ends with 1 and starts with some number under a million
# n -> n/2 | n is even
# n -> 3n + 1 | n is odd
def next(n):
if n % 2 == 0:
return int(n/2)
else:
return (3*n + 1)
def sequence(n):
res = [n]
while res[-1] != 1:
res.append(next(res[-1]))
return res
def getLongestSequence(n):
seqLengths = [0] * n
seqLengths[0] = 1
for x in range(1, n):
i = x + 1
l = 1
while True:
if i == 1:
break
elif i < n + 1 and seqLengths[i - 1] > 0:
l = l + seqLengths[i - 1] - 1
break
else:
l = l + 1
i = next(i)
seqLengths[x] = l
print(x + 1, l)
return seqLengths
def main():
print("Hello, this is Patrick")
t = getLongestSequence(1000000)
m = t[0]
j = 0
for i in range(len(t)):
if t[i] > m:
m = t[i]
j = i
print("Max", j + 1, m)
if __name__ == "__main__":
main()

54
projecteuler/015/main.py Normal file
View File

@@ -0,0 +1,54 @@
import os
import math
import numpy as np
# Given a grid with start in one corner and goal in opposite corner, find
# the number of paths you can take from start to goal. Do this for a grid
# of 20 by 20
def gridRoutes(x, y, gs):
res = 0
if gs[x][y] > 0:
res = gs[x][y]
else:
if y > x:
h = x
x = y
y = h
if y == 1:
res = x + 1
else:
res = gridRoutes(x - 1, y, gs) + gridRoutes(x, y - 1, gs)
gs[x][y] = res
# print(x, y, res)
return res
def dumbGridRoutes(x, y):
if x == 1:
return y + 1
elif y == 1:
return x + 1
else:
return dumbGridRoutes(x, y - 1) + dumbGridRoutes(x - 1, y)
def main():
print("Hello, this is Patrick")
gss = [0] * 21
for i in range(21):
gss[i] = [0] * 21
g = gridRoutes(20, 20, gss)
# dg = dumbGridRoutes(3, 2)
print(g)
# print(gss)
if __name__ == "__main__":
main()

20
projecteuler/016/main.py Normal file
View File

@@ -0,0 +1,20 @@
import os
import math
import numpy as np
# Find the sum of all the digits of 2 ^ 1000
def main():
print("Hello, this is Patrick")
p = pow(2, 1000)
s = str(p)
r = 0
for c in s:
r = r + int(c)
print(r)
if __name__ == "__main__":
main()

77
projecteuler/017/main.py Normal file
View File

@@ -0,0 +1,77 @@
import os
import math
import numpy as np
# Find the total number of letters needed to spell out all the numbers up to
# and including 1000
lengths = {
1 : 3, # one
2 : 3, # two
3 : 5, # three
4 : 4, # four
5 : 4, # five
6 : 3, # six
7 : 5, # seven
8 : 5, # eight
9 : 4, # nine
10 : 3, # ten
11 : 6, # eleven
12 : 6, # twelve
13 : 8, # thirteen
14 : 8, # fourteen
15 : 7, # fifteen
16 : 7, # sixteen
17 : 9, # seventeen
18 : 8, # eighteen
19 : 8, # nineteen
20 : 6, # twenty
30 : 6, # thirty
40 : 5, # fourty
50 : 5, # fifty
60 : 5, # sixty
70 : 7, # seventy
80 : 6, # eighty
90 : 6, # ninety
100 : 7 # hundred (the number of hundreds will be put in front)
}
def getNumberLength(n):
res = 0
if n == 1000:
return 11
if n % 100 < 20 and n % 100 != 0:
res = res + lengths[n % 100]
n = n // 100
else:
if n % 10 != 0:
res = res + lengths[n % 10]
n = n // 10
if n % 10 != 0:
res = res + lengths[(n % 10) * 10]
n = n // 10
if n == 0:
return res
else:
a = 3
if res == 0:
a = 0
res = res + a + lengths[100] + lengths[n]
return res
def main():
print("Hello, this is Patrick")
print(getNumberLength(100))
result = sum(list(map(lambda x: getNumberLength(x), range(1, 1001))))
print(result)
if __name__ == "__main__":
main()

71
projecteuler/018/main.py Normal file
View File

@@ -0,0 +1,71 @@
import os
import math
import numpy as np
# Find the maximum path sum of the triangle below, if you follow a path that
# starts at the top and goes down, choosing one of either value below you
# 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
def getMaxPath(t):
t0 = t[0][0]
if len(t) == 1:
return t0
# if len(t) == 2:
# return t0 + max(t[1][0], t[1][1])
left = list(map(lambda row: row[:-1], t[1:]))
right = list(map(lambda row: row[1:], t[1:]))
return t0 + max(getMaxPath(left), getMaxPath(right))
def main():
print("Hello, this is Patrick")
triangle = '''
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'''
ts = triangle.strip().split('\n')
t = []
for x in ts:
t.append(list(map(lambda y: int(y), x.split(' '))))
r = getMaxPath(t)
print(r)
if __name__ == "__main__":
main()

24
projecteuler/019/main.py Normal file
View File

@@ -0,0 +1,24 @@
import os
import datetime
# How many sundays fell on the first of the month in the twentieth century?
def getFirsts(minYear, maxYear):
res = 0
for year in range(minYear, maxYear + 1):
for month in range(1, 13):
if datetime.datetime(year, month, 1).weekday() == 6:
res = res + 1
return res
def main():
print("Hello, this is Patrick")
print(getFirsts(1901, 2000))
if __name__ == "__main__":
main()

30
projecteuler/020/main.py Normal file
View File

@@ -0,0 +1,30 @@
import os
import math
import numpy as np
# Get the sum of all the digits of 100!
def fac(n):
if n == 0:
return 1
return n * fac(n-1)
def sumDigits(n):
s = str(n)
res = 0
for c in s:
res = res + int(c)
return res
def main():
print("Hello, this is Patrick")
f100 = fac(100)
s100 = sumDigits(f100)
print(s100)
if __name__ == "__main__":
main()

47
projecteuler/021/main.py Normal file
View File

@@ -0,0 +1,47 @@
import os
import math
import numpy as np
# Evaluate the sum all amicable numbers under 10000
# A pair of number is amicable if the sum of their proper divisors is equal
# to each other, they are then both called amicable numbers
def getDivs(n):
ds = [True] * math.ceil(n/2)
for i in range(1, len(ds)):
if ds[i] and n % (i+1) != 0:
j = i
while j < len(ds):
ds[j] = False
j = j + i + 1
res = []
for i in range(0, len(ds)):
if ds[i]:
res.append(i+1)
return res
def getSumDivs(n):
return sum(getDivs(n))
def main():
print("Hello, this is Patrick")
dsums = [getSumDivs(x) for x in range(1, 10001)]
res = 0
for i in range(len(dsums)):
di = dsums[i]
if (i+1) != di:
if di-1 < len(dsums):
if i+1 == dsums[di-1]:
res = res + i + 1
else:
dj = getSumDivs(di)
if i+1 == dj:
res = res + i + 1
print(res)
if __name__ == "__main__":
main()

40
projecteuler/022/main.py Normal file
View File

@@ -0,0 +1,40 @@
import os
import math
import numpy as np
# Calculate the sum of all scores of the names in the textfile, where
# the score is the product of the sorted position and
# sum of alphabetic values of its letters
def charScore(c):
assert len(c) == 1
return ord(c.lower()) - 96
def strScore(s):
res = 0
for c in s:
res = res + charScore(c)
return res
def main():
print("Hello, this is Patrick")
f = open("names.txt", 'r')
names = f.readline()
f.close()
names = names.strip('\"').split("\",\"")
names.sort()
scores = []
for i in range(len(names)):
n = names[i]
score = strScore(n) * (i + 1)
scores.append(score)
print(sum(scores))
if __name__ == "__main__":
main()

File diff suppressed because one or more lines are too long

60
projecteuler/023/main.py Normal file
View File

@@ -0,0 +1,60 @@
import os
import math
import numpy as np
# Find the sum of all positive integers which cannot be written as the sum
# of two abundant numbers.
# A number is abundant if its properdivisors sum to
# more than the original number, e.g. 12 is abundant, since 12 can be divided
# by 1, 2, 3, 4, 6 = 16
# It can be proven that all numbers above 28123 can be written as the sum
# of 2 abundant numbers
def getDivisors(n):
divs = [True] * math.ceil(n/2)
for x in range(1, len(divs)):
if divs[x] and n % (x + 1) != 0:
y = x
while y < len(divs):
divs[y] = False
y = y + x + 1
res = []
for x in range(len(divs)):
if divs[x]:
res.append(x + 1)
return res
def isAbundant(n):
return sum(getDivisors(n)) > n
def main():
print("Hello, this is Patrick")
m = 28123
a = list(filter(isAbundant, range(1, m+1)))
# We are assuming that the abundants are sorted
sums = set([])
for i in range(len(a)):
for j in range(i, len(a)):
s = a[i] + a[j]
if s > m:
break
else:
#print(s)
sums.add(s)
nonsums = set(range(1, m+1))
nonsums.difference_update(sums)
# print(nonsums)
print(sum(nonsums))
if __name__ == "__main__":
main()

44
projecteuler/024/main.py Normal file
View File

@@ -0,0 +1,44 @@
# Get the millionth lexicographic permutation of the digits
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
import math
def fac(n):
if n == 0:
return 1
else:
return n * fac(n-1)
def getPermutation(n, s):
p = sorted(s)
l = len(s)
x = n - 1
seq = []
assert n > 0
assert l > 0
assert n <= fac(l)
f = fac(l)
while l > 0:
part = math.floor(f / l)
f /= l
y = math.floor(x / part)
x -= y * part
seq.append(y)
l -= 1
res = []
for se in seq:
res.append(p.pop(se))
return res
def main():
print("Hello, this is Patrick")
r = getPermutation(1000000, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(r)
if __name__ == "__main__":
main()

43
projecteuler/025/main.py Normal file
View File

@@ -0,0 +1,43 @@
# Get the index of the first Fibonacci number that contains 1000 digits
def dumbfib(n):
if n < 3:
return 1
else:
return dumbfib(n - 2) + dumbfib(n - 1)
def fib(n):
if n < 3:
return 1
else:
i = 2
res = [1, 1]
while i < n:
i += 1
res.append(res[-1] + res[-2])
return res[-1]
def getLargeFib(x):
if x < 2:
return 1
fibs = [1, 1]
while fibs[-1] < x:
fibs.append(fibs[-1] + fibs[-2])
return len(fibs)
def main():
print("Hello, this is Patrick")
# print(dumbfib(10))
# print(fib(10000))
r = getLargeFib(pow(10, 999))
print(r)
if __name__ == "__main__":
main()

84
projecteuler/026/main.py Normal file
View File

@@ -0,0 +1,84 @@
# Find the number d < 1000 for which 1 / d has the longest recurring cycle
# in its decimal fraction part
# It seems like the cycle is never longer than the longest of the cycle length of any of its prime divisors
# So say we want to know the length for d and d = a * b, then the cycle for d has the same length as either the cycle for a or b, whichever is longer.
# So it seems we then only have to check the primes, so first let's get a prime finder in here
import numpy as np
import math
def maxIndex(ns):
result = 0
m = ns[0]
for i in range(len(ns)):
if ns[i] > m:
result = i
m = ns[i]
return result
def getPrimes(n):
primes = [1 for p in range(n)]
primes[0] = 0
primes[1] = 0
x = 2
while x < np.sqrt(n):
if primes[x] == 1:
for i in range(x+x, n, x):
primes[i] = 0
x += 1
result = []
for i in range(n):
if primes[i]:
result.append(i)
return result
# Now we need to find out the recurring cycle length for any number
# As a benefit for only checking prime number, we know that the cycles will always immediately start after the .'s
def cycleLength(n):
l = int(math.log10(n)) + 1
y = 1
power = pow(10,l)
result = 1
while True:
x = (y * power) // n
rest = y * power - x * n
if rest == 0:
return 0
elif rest == 1:
break
else:
y = rest
result += 1
return result * l
def main():
print("Hello, this is Patrick")
ps = getPrimes(1000)
cyclelengths = [cycleLength(p) for p in ps]
for i in range(len(ps)):
print(f"{ps[i]} has length: {cyclelengths[i]}")
print(f"Biggest cycle is for {ps[maxIndex(cyclelengths)]} with length {max(cyclelengths)}")
if __name__ == "__main__":
main()

69
projecteuler/027/main.py Normal file
View File

@@ -0,0 +1,69 @@
# Quadratic primes
# Consider quadratics of the form:
# n^2 + an + b, where abs(a) < 1000 and abs(b) <= 1000
# Find the product of the coefficients, a * b, for the quadratic expression that
# produces the maximum number of primes for consecutive values of n, starting from n = 0
import numpy as np
import math
def quad(a, b, n):
return n**2 + a * n + b
# Thing that immediately stands out is that b always needs to be prime itself,
# since for n=0 only b remains, so that thins the pool a lot
# So get the prime thingy out again
def getPrimes(n):
primes = [1 for p in range(n)]
primes[0] = 0
primes[1] = 0
x = 2
while x < np.sqrt(n):
if primes[x] == 1:
for i in range(x+x, n, x):
primes[i] = 0
x += 1
result = []
for i in range(n):
if primes[i]:
result.append(i)
return result
def getPrimeSequenceLength(a, b, primes):
n = 0
while True:
if quad(a, b, n) in primes:
n += 1
else:
break
return n - 1
def main():
print("Hello, this is Patrick")
ps = getPrimes(1000000)
littleps = list(filter(lambda p: p < 1000, ps))
maxprod = 0
maxlength = 0
for b in littleps:
for a in range(-b, 1000):
psl = getPrimeSequenceLength(a, b, ps)
if psl > maxlength:
maxlength = psl
maxprod = a * b
print(f"The maximum prime sequence {maxlength} was found for {maxprod}")
if __name__ == "__main__":
main()

31
projecteuler/028/main.py Normal file
View File

@@ -0,0 +1,31 @@
# Number spiral diagonals
# Find the sum of the numbers on the diagonals of a 1001 by 1001 spiral
def sumSpiralDiagonals(n):
assert n % 2 == 1
if n == 1:
return 1
result = 0
corner = 1
for i in range(1, n+1, 2):
if i == 1:
result += corner
else:
for j in range(4):
corner += i - 1
result += corner
return result
def main():
print("Hello, this is Patrick")
print(sumSpiralDiagonals(1001))
if __name__ == "__main__":
main()

20
projecteuler/029/main.py Normal file
View File

@@ -0,0 +1,20 @@
# Distinct Powers
# Consider all integer combinations of a^b for 2 <= a <= 100 and 2 <= b <= 100
# How many distinct terms are there in that sequence
import math
def main():
print("Hello, this is Patrick")
s = set()
for a in range(2, 101):
for b in range(2, 101):
s.add(a**b)
print(len(s))
if __name__ == "__main__":
main()

26
projecteuler/030/main.py Normal file
View File

@@ -0,0 +1,26 @@
# Digit fifth powers
# 1634, 8208 and 9474 are the only number that can be written as the sum of the fourth powers of their digits
# Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits
# Through some googling, we found an upper bound of the result at 6*9^5 = 354294
# So, we can just bruteforce it, not that big of a search space
def intToList(n):
return [int(d) for d in str(n)]
def sumIntPowers(n, p=5):
return sum([d**p for d in intToList(n)])
def main():
print("Hello, this is Patrick")
result = 0
for n in range(10, 999999):
if n == sumIntPowers(n):
result += n
print(result)
if __name__ == "__main__":
main()

32
projecteuler/031/main.py Normal file
View File

@@ -0,0 +1,32 @@
# Coin sums
# You have coins for 1p, 2p, 5p, 10p, 20p, 50p, 100p and 200p
# Find out how many ways there are to pay 200p
def count(S, n, N):
if N == 0:
return 1
if N < 0 or n < 0:
return 0
# Case 1. include current coin S[n] in solution and recur
# with remaining change (N - S[n]) with same number of coins
incl = count(S, n, N - S[n])
# Case 2. exclude current coin S[n] from solution and recur
# for remaining coins (n - 1)
excl = count(S, n - 1, N)
# return total ways by including or excluding current coin
return incl + excl
if __name__ == '__main__':
S = [1, 2, 5, 10, 20, 50, 100, 200]
N = 200
print("Total number of ways to get desired change is", count(S, len(S) - 1, N))

53
projecteuler/032/main.py Normal file
View File

@@ -0,0 +1,53 @@
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
# The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
# Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
# HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
# So, we only need inputs where the summands are of size 5 and the output of size 4
from itertools import combinations
from itertools import permutations
def splits(input, left, right):
assert len(input) == left + right
result = []
combis = combinations(input, left)
for c in combis:
r = list(set(input) - set(c))
result.append((list(c), r))
return result
def check(series):
result = set()
for i in range(4):
# print("Testing", toInt(series[0:i+1]) , toInt(series[i+1:5]) , toInt(series[5:]))
if toInt(series[0:i+1]) * toInt(series[i+1:5]) == toInt(series[5:]):
result.add(toInt(series[5:]))
return result
def toInt(l):
return int("".join(list(map(str,l))))
def main():
print("Hello, this is Patrick")
digits = range(1, 10)
perms = permutations(digits)
products = set()
for perm in perms:
products.update(check(perm))
print(products)
print(sum(products))
if __name__ == "__main__":
main()

53
projecteuler/033/main.py Normal file
View File

@@ -0,0 +1,53 @@
'''
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
'''
def listify(i):
return [int(x) for x in str(i)]
def check(num, denom):
result = False
frac = num / denom
lnum = listify(num)
ldenom = listify(denom)
if lnum[0] == ldenom[0] and ldenom[1] != 0:
result = lnum[1] / ldenom[1] == frac
elif lnum[1] == ldenom[0] and ldenom[1] != 0:
result = lnum[0] / ldenom[1] == frac
elif lnum[0] == ldenom[1]:
result = lnum[1] / ldenom[0] == frac
elif lnum[1] == ldenom[1]:
result = lnum[0] / ldenom[0] == frac
return result
def main():
print("Hello, this is Patrick")
numres = 1
denomres = 1
for denom in range(11, 100):
for num in range(10, denom):
if not (denom % 10 == 0 and num % 10 == 0) and check(num, denom):
numres *= num
denomres *= denom
print(num, denom)
print(f"{numres}/{denomres}")
if __name__ == "__main__":
main()

31
projecteuler/034/main.py Normal file
View File

@@ -0,0 +1,31 @@
'''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
'''
import math
def listify(i):
return [int(x) for x in str(i)]
def check(i):
l = [math.factorial(x) for x in listify(i)]
return i == sum(l)
def main():
print("This is Patrick")
res = 0
for i in range(1000000):
if check(i):
res += i
print(i)
print(res - 3)
if __name__ == "__main__":
main()

58
projecteuler/035/main.py Normal file
View File

@@ -0,0 +1,58 @@
'''
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def rotate(n):
if n < 10:
return n
else:
l = n % 10
return l * 10**(len(str(n)) - 1) + n // 10
def isCircular(p, primes):
result = True
cur = rotate(p)
while cur != p:
if cur not in primes:
result = False
break
cur = rotate(cur)
return result
def main():
print("Hello this is Patrick")
primes = sieve(1000000)
res = 0
for p in primes:
if isCircular(p, primes):
print(p)
res += 1
print("Number of circular primes:", res)
if __name__ == "__main__":
main()

29
projecteuler/036/main.py Normal file
View File

@@ -0,0 +1,29 @@
'''
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
'''
def isPalindrome(n):
return n == int(str(n)[::-1])
def makeBinary(n):
return int(bin(n)[2:])
def main():
print("Hello this is Patrick")
print(makeBinary(8))
summand = 0
for n in range(1000000):
if isPalindrome(n) and isPalindrome(makeBinary(n)):
summand += n
print(summand)
if __name__ == "__main__":
main()

53
projecteuler/037/main.py Normal file
View File

@@ -0,0 +1,53 @@
'''
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
Note: 2, 3, 5, and 7 are not considered to be truncatable primes.
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def isTruncable(n, primes):
s = str(n)
for i in range(len(s)):
if int(s[:i+1]) not in primes or int(s[i:]) not in primes:
return False
return True
def main():
print("Hello this is Patrick")
primes = set(sieve(10000000))
truncs = []
i = 11
while len(truncs) < 11:
if isTruncable(i, primes):
truncs.append(i)
print(truncs)
i += 2
print(f"Trunc sum: {sum(truncs)}")
if __name__ == "__main__":
main()

57
projecteuler/038/main.py Normal file
View File

@@ -0,0 +1,57 @@
'''
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?
'''
def conLength(n):
i = 1
p = len(str(n))
while p < 9:
i += 1
p += len(str(i * n))
if p == 9:
return True
return False
def isPandigital(n):
digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}
if set(map(int, str(n))) == digits:
return True
return False
def concatProduct(n):
i = 1
d = n
while len(str(d)) < 9:
i += 1
d = int(str(d) + str(n * i))
return d
def main():
print("Hello this is Patrick")
m = 0
for i in range(1, 54321):
if conLength(i):
d = concatProduct(i)
if isPandigital(d) and d > m:
m = d
print(m)
if __name__ == "__main__":
main()

29
projecteuler/039/main.py Normal file
View File

@@ -0,0 +1,29 @@
'''
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?
'''
import math
def main():
print("Hello this is Patrick")
ps = [0]*1000
for a in range(1, 1000):
for b in range(1, 1000-a):
c2 = a**2 + b**2
r = math.sqrt(c2)
if c2 == int(r + 0.5) ** 2:
r = int(r + 0.5)
if a + b + r <= 1000:
ps[a + b + r - 1] += 1
print(ps.index(max(ps)) + 1)
if __name__ == "__main__":
main()

29
projecteuler/040/main.py Normal file
View File

@@ -0,0 +1,29 @@
'''An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
'''
def main():
print("Hello this is Patrick")
s = ""
n = 1
while len(s) < 1000000:
s += str(n)
n += 1
d = 1
for i in range(1, 7):
d *= int(s[10**i - 1])
print(d)
if __name__ == "__main__":
main()

49
projecteuler/041/main.py Normal file
View File

@@ -0,0 +1,49 @@
'''
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def isPandigital(n):
l = len(str(n))
digits = set(range(1, l+1))
if digits == set(map(int, str(n))):
return True
return False
def main():
print("Hello this is Patrick")
primes = sieve(987654321)
print("Calculated enough primes")
r = 1
while not isPandigital(primes[-1 * r]):
r += 1
print(primes[-1 * r])
if __name__ == "__main__":
main()

48
projecteuler/042/main.py Normal file

File diff suppressed because one or more lines are too long

46
projecteuler/043/main.py Normal file
View File

@@ -0,0 +1,46 @@
'''
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.
'''
from itertools import permutations
def listToNum(l):
s = ''.join(map(str, l))
return int(s)
def check(l):
primes = [2, 3, 5, 7, 11, 13, 17]
for i in range(1, 8):
# print(listToNum(l[i:i+3]))
if listToNum(l[i:i+3]) % primes[i-1] != 0:
return False
return True
def main():
print("Hello this is Patrick")
summand = 0
# print(check(list(map(int, str(1406357289)))))
for p in permutations(range(10)):
if check(p):
summand += listToNum(p)
print(summand)
if __name__ == "__main__":
main()

48
projecteuler/044/main.py Normal file
View File

@@ -0,0 +1,48 @@
'''
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk Pj| is minimised; what is the value of D?
'''
import math
def p(n):
return int(n * (3 * n - 1) / 2)
def isTriangle(n, triangleSet, triangleList):
if n > triangleList[-1]:
toBeat = triangleList[-1]
m = len(triangleList)
while toBeat < n:
m += 1
toBeat = p(m)
triangleList.append(toBeat)
triangleSet.add(toBeat)
return n == triangleList[-1]
else:
return n in triangleSet
def main():
print("Hello this is Patrick")
bestDif = math.inf
triangleList = [1, 5]
triangleSet = set(triangleList)
for i in range(2, 10000):
for j in range(1, i):
if isTriangle(p(i) - p(j), triangleSet, triangleList) and isTriangle(p(i) + p(j), triangleSet, triangleList):
bestDif = min(bestDif, abs(p(i) - p(j)))
print(bestDif)
if __name__ == "__main__":
main()

35
projecteuler/045/main.py Normal file
View File

@@ -0,0 +1,35 @@
'''
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
'''
# Observe that every other triangle number is also a hexagonal number, so the 1st, the 3rd, 5th, etc.
# So we only need to check all the uneven n triangle numbers to be pentagonal
# In addition, we can check if a number is pentagonal by checking if sqrt(1 + 24 n) % 6 == 5
import math
def t(n):
return n * (n+1) / 2
def isPentagonal(x):
return math.sqrt(1 + 24 * x) % 6 == 5
def main():
print("Hello this is Patrick")
n = 287
while not isPentagonal(t(n)):
n += 2
print(t(n))
if __name__ == "__main__":
main()

60
projecteuler/046/main.py Normal file
View File

@@ -0,0 +1,60 @@
'''
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
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?
'''
# So I guess I just go past all odd non-prime numbers and keep subtracting all double squares that fit and see if the rest is a prime
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def main():
print("Hello this is Patrick")
end = 10000
primes = set(sieve(end))
for n in range(9, end, 2):
termination = True
if n not in primes:
x = 1
while n - 2 * x*x > 0:
if n - 2 * x*x in primes:
termination = False
break
x += 1
if termination:
print(n)
break
if __name__ == "__main__":
main()

68
projecteuler/047/main.py Normal file
View File

@@ -0,0 +1,68 @@
'''
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def primeFactors(n, primes):
res = []
for p in primes:
if n % p == 0:
res.append(p)
while n % p == 0:
n /= p
return res
def main():
print("Hello this is Patrick")
end = 1000000
primeList = sieve(end)
primeSet = set(primeList)
consecs = 0
for n in range(100000, end):
if n not in primeSet:
if len(primeFactors(n, primeList)) == 4:
consecs += 1
else:
consecs = 0
else:
consecs = 0
if consecs == 4:
for i in range(n-3, n+1):
print(i, primeFactors(i, primeList))
break
if __name__ == "__main__":
main()

18
projecteuler/048/main.py Normal file
View File

@@ -0,0 +1,18 @@
'''
The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
'''
def main():
print("Hello this is Patrick")
s = 0
for i in range(1,1001):
s += pow(i, i,10**10)
print(s % 10**10)
if __name__ == "__main__":
main()

54
projecteuler/049/main.py Normal file
View File

@@ -0,0 +1,54 @@
'''
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?
'''
import math
import numpy as np
from itertools import permutations
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def digitToList(n):
return [int(c) for c in str(n)]
def listToDigit(l):
res = 0
for i in l:
res = 10 * res + i
return res
def main():
print("Hello this is Patrick")
primeSet = set(sieve(10000)) - set(sieve(1000))
primeList = list(primeSet)
for p in primeList:
perms = list(set(map(listToDigit, list(permutations(digitToList(p))))))
for perm in perms:
if p != perm and perm in primeSet:
if max(p, perm) + abs(p - perm) in primeSet and max(p, perm) + abs(p - perm) in perms:
print(min(p, perm), max(p, perm), max(p, perm) + abs(p - perm))
if __name__ == "__main__":
main()

117
projecteuler/050/main.py Normal file
View File

@@ -0,0 +1,117 @@
'''
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?
'''
import math
import numpy as np
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
# Note: this subset sum implementation only backtracks the sum with the smallest values as possible
def subsetSum(elements, target):
dyn = []
for _ in range(len(elements) + 1):
dyn.append([True])
for _ in range(target):
dyn[0].append(False)
for i in range(1, len(elements) + 1):
for j in range(1, target + 1):
if elements[i-1] > j:
dyn[i].append(dyn[i-1][j])
else:
dyn[i].append(dyn[i-1][j] or dyn[i-1][j - elements[i-1]])
if not dyn[-1][-1]:
return []
j = target
i = len(elements)
res = []
while j > 0:
while dyn[i - 1][j]:
i -= 1
curEl = elements[i - 1]
j -= curEl
res.append(curEl)
return res
def main():
print("Hello this is Patrick")
target = 1000000
primeList = sieve(target)
primeSet = set(primeList)
numberofprimes = len(primeList)
# s = 0
# n = 0
# while s < target:
# s += primeList[n]
# n += 1
# print(numberofprimes)
# print(n - 1, s - primeList[n-1])
# So the number of options is very, very, very very large, we can't brute force this
# print(math.factorial(numberofprimes) // (math.factorial(n-1) * math.factorial(numberofprimes - (n-1))))
# Additionally, this is exactly subset sum for all primes from big to small, since we probably want an as high as possible prime
# longest = 0
# prime = 0
# for p in reversed(primeList):
# l = subsetSum(primeList, p)
# if len(l) > longest:
# longest = len(l)
# prime = p
# print(prime)
# Well it seems I completely misinterpreted the question and did something way more difficult than was intended
prime = 0
longest = 0
for i in range(len(primeList)):
s = 0
primes = []
for p in primeList[i:]:
s += p
primes.append(p)
if s >= target:
break
if s in primeSet and len(primes) > longest:
prime = s
longest = len(primes)
print(prime)
if __name__ == "__main__":
main()

76
projecteuler/051/main.py Normal file
View File

@@ -0,0 +1,76 @@
'''
By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, 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.
'''
import numpy as np
import math
import time
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
# Does generate all families that can be made for that number, so that consists of multiple families together
def families(num):
result = []
variedDigits = set()
digits = [int(d) for d in str(num)]
for i in range(len(digits)):
if not i in variedDigits:
buddies = []
for j in range(len(digits)):
if digits[i] == digits[j]:
buddies.append(j)
variedDigits.add(j)
r = digits[:]
for n in range(10):
for bud in buddies:
r[bud] = n
maybeResult = int("".join([str(_r) for _r in r]))
result.append(maybeResult)
return result
def findPrimeFamily(length):
primes = sieve(1000000)
primeSet = set(primes)
for p in primes:
primeFamilies = families(p)
for i in range(len(primeFamilies) // 10):
counter = 0
for pf in primeFamilies[10*i:10*i+10]:
if pf in primeSet and len(str(pf)) == len(str(p)):
counter += 1
if counter >= length:
return [x for x in primeFamilies[10*i:10*i+10] if x in primeSet]
def main():
print("Hello this is Patrick")
t0 = time.time()
print(findPrimeFamily(8), time.time() - t0)
if __name__ == "__main__":
main()

37
projecteuler/052/main.py Normal file
View File

@@ -0,0 +1,37 @@
'''
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.
'''
import time
import math
def findMultiples(factors):
result = 1
while True:
products = [[s for s in str(f * result)] for f in factors]
sresult = [s for s in str(result)]
skip = False
for i in range(len(products) - 1):
if len(products[i]) != len(sresult) or set(products[i]) != set(sresult):
skip = True
if skip:
result += 1
continue
return result
def main():
print("Hello, this is Patrick")
t0 = time.time()
print(findMultiples([2, 3, 4, 5, 6]), time.time() - t0)
if __name__ == "__main__":
main()

40
projecteuler/053/main.py Normal file
View File

@@ -0,0 +1,40 @@
'''
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation,
.
In general,
, where , , and .
It is not until , that a value exceeds one-million:
.
How many, not necessarily distinct, values of
for , are greater than one-million?
'''
# Okay I have to admit that it looks really bad without the math equations
import time
import math
def main():
print("Hello, this is Patrick")
t0 = time.time()
tooBig = 1000000
counter = 0
for n in range(1, 101):
for r in range(1, n+1):
if math.comb(n, r) > tooBig:
counter += 1
print(counter, time.time() - t0)
if __name__ == "__main__":
main()

270
projecteuler/054/main.py Normal file
View File

@@ -0,0 +1,270 @@
'''
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All cards of the same suit.
Full House: Three of a kind and a pair.
Four of a Kind: Four cards of the same value.
Straight Flush: All cards are consecutive values of same suit.
Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
Consider the following five hands dealt to two players:
Hand Player 1 Player 2 Winner
1 5H 5C 6S 7S KD
Pair of Fives
2C 3S 8S 8D TD
Pair of Eights
Player 2
2 5D 8C 9S JS AC
Highest card Ace
2C 5C 7D 8S QH
Highest card Queen
Player 1
3 2D 9C AS AH AC
Three Aces
3D 6D 7D TD QD
Flush with Diamonds
Player 2
4 4D 6S 9H QH QC
Pair of Queens
Highest card Nine
3D 6D 7H QD QS
Pair of Queens
Highest card Seven
Player 1
5 2H 2D 4C 4D 4S
Full House
With Three Fours
3C 3D 3S 9S 9D
Full House
with Three Threes
Player 1
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?
'''
import time
import math
from enum import IntEnum, Enum, auto
class PokerHand(IntEnum):
HIGH = 0
PAIR = 1
TWOPAIR = 2
THREEOFAKIND = 3
STRAIGHT = 4
FLUSH = 5
FULLHOUSE = 6
FOUROFAKIND = 7
STRAIGHTFLUSH = 8
ROYALFLUSH = 9
class Suit(Enum):
HEARTS = auto()
CLUBS = auto()
SPADES = auto()
DIAMONDS = auto()
class Value(IntEnum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 11
QUEEN = 12
KING = 13
ACE = 14
def equal(l):
return all(value == l[0] for value in l)
def freqTable(l):
table = {}
for num in l:
if num in table.keys():
table[num] += 1
else:
table[num] = 1
return table
def textToCard(s):
suit = None
value = None
if s[1] == "H":
suit = Suit.HEARTS
elif s[1] == "C":
suit = Suit.CLUBS
elif s[1] == "S":
suit = Suit.SPADES
else:
suit = Suit.DIAMONDS
if s[0].isnumeric():
value = Value(int(s[0]))
elif s[0] == "T":
value = Value.TEN
elif s[0] == "J":
value = Value.JACK
elif s[0] == "Q":
value = Value.QUEEN
elif s[0] == "K":
value = Value.KING
else:
value = Value.ACE
return suit, value
def classifyHand(hand):
sameSuit = equal([suit for (suit,_) in hand])
values = [value for (_,value) in hand]
values.sort()
if set(values) == set([Value.ACE, Value.KING, Value.QUEEN, Value.JACK, Value.TEN]) and sameSuit:
return PokerHand.ROYALFLUSH
elif all(dif == 1 for dif in [values[i+1] - values[i] for i in range(4)]) and sameSuit:
return PokerHand.STRAIGHTFLUSH
elif equal(values[:4]) or equal(values[1:]):
return PokerHand.FOUROFAKIND
elif (equal(values[:3]) and equal(values[3:])) or (equal(values[2:]) and equal(values[:2])):
return PokerHand.FULLHOUSE
elif sameSuit:
return PokerHand.FLUSH
elif all(dif == 1 for dif in [values[i+1] - values[i] for i in range(4)]):
return PokerHand.STRAIGHT
elif equal(values[:3]) or equal(values[1:4]) or equal(values[2:]):
return PokerHand.THREEOFAKIND
elif (equal(values[:2]) and (equal(values[2:4]) or equal(values[3:]))) or (equal(values[1:3]) and equal(values[3:])):
return PokerHand.TWOPAIR
elif equal(values[:2]) or equal(values[1:3]) or equal(values[2:4]) or equal(values[3:]):
return PokerHand.PAIR
return PokerHand.HIGH
def winner(s1, s2):
hand1 = [textToCard(s) for s in s1]
hand2 = [textToCard(s) for s in s2]
result1 = classifyHand(hand1)
result2 = classifyHand(hand2)
if result1 != result2:
return result1 > result2
values1 = [value for (_,value) in hand1]
values2 = [value for (_,value) in hand2]
values1.sort(reverse=True)
values2.sort(reverse=True)
table1 = freqTable(values1)
table2 = freqTable(values2)
if result1 == PokerHand.FOUROFAKIND:
four1 = None
four2 = None
for key in table1.keys():
if table1[key] == 4:
four1 = key
for key in table2.keys():
if table2[key] == 4:
four2 = key
return four1 > four2
elif result1 == PokerHand.FULLHOUSE:
three1 = None
three2 = None
for key in table1.keys():
if table1[key] == 3:
three1 = key
for key in table2.keys():
if table2[key] == 3:
three2 = key
return three1 > three2
elif result1 == PokerHand.THREEOFAKIND:
three1 = None
three2 = None
for key in table1.keys():
if table1[key] == 3:
three1 = key
for key in table2.keys():
if table2[key] == 3:
three2 = key
return three1 > three2
elif result1 == PokerHand.TWOPAIR:
one1 = None
one2 = None
for key in table1.keys():
if table1[key] == 1:
one1 = key
for key in table2.keys():
if table2[key] == 1:
one2 = key
pairs1 = values1.copy()
pairs1.remove(one1)
pairs1.sort(reverse=True)
pairs2 = values2.copy()
pairs2.remove(one2)
pairs2.sort(reverse=True)
if pairs1 == pairs2:
return one1 > one2
else:
return pairs1 > pairs2
elif result1 == PokerHand.PAIR:
pair1 = None
pair2 = None
for key in table1.keys():
if table1[key] == 2:
pair1 = key
for key in table2.keys():
if table2[key] == 2:
pair2 = key
rest1 = values1.copy()
rest1.remove(pair1)
rest1.remove(pair1)
rest1.sort(reverse=True)
rest2 = values2.copy()
rest2.remove(pair2)
rest2.remove(pair2)
rest2.sort(reverse=True)
if pair1 == pair2:
return rest1 > rest2
else:
return pair1 > pair2
return values1 > values2
def main():
print("Hello, this is Patrick")
t0 = time.time()
counter = 0
with open("54/poker.txt", 'r') as reader:
for line in reader:
words = line.split()
counter += winner(words[:5], words[5:])
print(counter, time.time() - t0)
if __name__ == "__main__":
main()

1000
projecteuler/054/poker.txt Normal file

File diff suppressed because it is too large Load Diff

83
projecteuler/055/main.py Normal file
View File

@@ -0,0 +1,83 @@
'''
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
'''
import time
import math
def reverseInt(n):
res = 0
while n > 0:
res *= 10
res += n % 10
n = n // 10
return res
def palint(n):
if n == 0:
return True
if int(math.log10(n)) + 1 <= 1:
return True
s = str(n)
if s[0] != s[-1]:
return False
if len(s) == 2:
return True
return palint(int(s[1:-1]))
def lychrel(n, iterations):
res = n
visited = set()
for _ in range(iterations):
visited.add(res)
res += reverseInt(res)
if palint(res):
return res, visited
return False, visited
def main():
print("Hello, this is Patrick")
t0 = time.time()
counter = 0
lychrels = set()
nonLychrels = set()
for i in range(1, 10000):
if i in lychrels:
counter += 1
elif i in nonLychrels:
continue
else:
ans, visited = lychrel(i, 50)
if ans:
nonLychrels = nonLychrels.union(visited)
else:
lychrels = lychrels.union(visited)
counter += 1
print(counter, time.time() - t0)
if __name__ == "__main__":
main()

37
projecteuler/056/main.py Normal file
View File

@@ -0,0 +1,37 @@
'''
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
'''
import time
import math
def intSum(n):
res = 0
while n > 0:
res += n % 10
n //= 10
return res
def main():
print("Hello, this is Patrick")
t0 = time.time()
maxSum = 0
for a in range(100):
if a % 10 == 0:
continue
for b in range(100):
if b % 10 == 0:
continue
if intSum(a**b) > maxSum:
maxSum = intSum(a**b)
print(maxSum, time.time() - t0)
if __name__ == "__main__":
main()

59
projecteuler/057/main.py Normal file
View File

@@ -0,0 +1,59 @@
'''
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
By expanding this for the first four iterations, we get:
The next three expansions are
,
, and
, but the eighth expansion,
, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?
'''
import math
import time
def t(n, dDict):
assert n >= 0
if n == 0:
return 1, 1
num, denom = d(n-1, dDict)
return (num + denom, denom)
def d(n, dDict):
assert n >= 0
if n == 0:
return 1, 2
if n in dDict.keys():
return dDict[n]
num, denom = d(n-1, dDict)
r = (denom, 2 * denom + num)
dDict[n] = r
return r
def main():
print("Hello, this is Patrick")
t0 = time.time()
counter = 0
dDict = {}
for n in range(1001):
num, denom = t(n, dDict)
if len(str(num)) > len(str(denom)):
counter += 1
print(counter, time.time() - t0)
if __name__ == "__main__":
main()

67
projecteuler/058/main.py Normal file
View File

@@ -0,0 +1,67 @@
'''
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
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%?
'''
import time
import math
import numpy as np
from sympy import isprime
def sieve(n):
assert n > 1
ns = [True] * n
for i in range(2, math.ceil(np.sqrt(n))):
if ns[i]:
j = pow(i, 2)
while j < n:
ns[j] = False
j = j + i
return [i for i,val in enumerate(ns) if val][2:]
def corners(n):
if n == 1:
return [1]
layer = list(range((n*2-3)**2+1, (n*2-1)**2+1))
cList = []
for i in range(4):
cList.append(layer[-1 - (2*n-2)*i])
return cList
def main():
print("Hello, this is Patrick")
t0 = time.time()
# primes = set(sieve(1000000000))
numberPrimes = 0
n = 2
while True:
cs = corners(n)
for c in cs:
if isprime(c):
numberPrimes += 1
if numberPrimes / ((n-1)*4 + 1) < 0.1:
print(n*2-1, time.time() - t0)
break
n += 1
if __name__ == "__main__":
main()

82
projecteuler/059/main.cpp Normal file
View File

@@ -0,0 +1,82 @@
/*
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower case characters. Using p059_cipher.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.
*/
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
cout << "Hello this is Patrick" << endl;
ifstream inFile;
inFile.open("../txts/cipher.txt");
if(!inFile){
cerr << "Unable to open file: ../txts/cipher.txt" << endl;
exit(1);
}
vector<unsigned char> encrypted;
while(true){
unsigned int current;
inFile >> current;
if(!inFile) break;
encrypted.push_back(current);
inFile.get();
}
inFile.close();
for(unsigned char i = 'a'; i <= 'z'; ++i){
for(unsigned char j = 'a'; j <= 'z'; ++j){
for(unsigned char k = 'a'; k <= 'z'; ++k){
const unsigned char key[] = {i,j,k};
vector<unsigned char> decoded;
for(size_t pos = 0; pos < encrypted.size(); pos++){
decoded.push_back(encrypted[pos] ^ key[pos % 3]);
}
bool valid = true;
for(auto d : decoded){
valid = (d >= ' ' && d <= ';');
valid |= (d >= 'A' && d <= 'z');
if(!valid){
break;
}
}
if(!valid){
continue;
}
cout << key << endl;
unsigned int asciiSum = 0;
for(auto d : decoded){
asciiSum += d;
cout << d;
}
cout << endl;
cout << asciiSum << endl;
return 0;
}
}
}
return 0;
}

108
projecteuler/059/main.py Normal file
View File

@@ -0,0 +1,108 @@
def compute():
bestkey = max(((x, y, z)
for x in range(97, 123) # ASCII lowercase 'a' to 'z'
for y in range(97, 123)
for z in range(97, 123)),
key=lambda key: get_score(decrypt(CIPHERTEXT, key)))
print(bestkey, decrypt(CIPHERTEXT, bestkey))
ans = sum(decrypt(CIPHERTEXT, bestkey))
return str(ans)
# Heuristical function that returns a penalty score, where lower is better.
def get_score(plaintext):
result = 0
for c in plaintext:
if 65 <= c <= 90: # ASCII uppercase 'A' to 'Z', good
result += 1
elif 97 <= c <= 122: # ASCII lowercase 'a' to 'z', excellent
result += 2
elif c < 0x20 or c == 0x7F: # ASCII control characters, very bad
result -= 10
return result
# Takes two sequences of integers and returns a list of integers.
def decrypt(ciphertext, key):
return [(c ^ key[i % len(key)]) for (i, c) in enumerate(ciphertext)]
CIPHERTEXT = [
36, 22, 80, 0, 0, 4, 23, 25, 19, 17, 88, 4, 4, 19, 21, 11, 88, 22, 23, 23,
29, 69, 12, 24, 0, 88, 25, 11, 12, 2, 10, 28, 5, 6, 12, 25, 10, 22, 80, 10,
30, 80, 10, 22, 21, 69, 23, 22, 69, 61, 5, 9, 29, 2, 66, 11, 80, 8, 23, 3,
17, 88, 19, 0, 20, 21, 7, 10, 17, 17, 29, 20, 69, 8, 17, 21, 29, 2, 22, 84,
80, 71, 60, 21, 69, 11, 5, 8, 21, 25, 22, 88, 3, 0, 10, 25, 0, 10, 5, 8,
88, 2, 0, 27, 25, 21, 10, 31, 6, 25, 2, 16, 21, 82, 69, 35, 63, 11, 88, 4,
13, 29, 80, 22, 13, 29, 22, 88, 31, 3, 88, 3, 0, 10, 25, 0, 11, 80, 10, 30,
80, 23, 29, 19, 12, 8, 2, 10, 27, 17, 9, 11, 45, 95, 88, 57, 69, 16, 17, 19,
29, 80, 23, 29, 19, 0, 22, 4, 9, 1, 80, 3, 23, 5, 11, 28, 92, 69, 9, 5,
12, 12, 21, 69, 13, 30, 0, 0, 0, 0, 27, 4, 0, 28, 28, 28, 84, 80, 4, 22,
80, 0, 20, 21, 2, 25, 30, 17, 88, 21, 29, 8, 2, 0, 11, 3, 12, 23, 30, 69,
30, 31, 23, 88, 4, 13, 29, 80, 0, 22, 4, 12, 10, 21, 69, 11, 5, 8, 88, 31,
3, 88, 4, 13, 17, 3, 69, 11, 21, 23, 17, 21, 22, 88, 65, 69, 83, 80, 84, 87,
68, 69, 83, 80, 84, 87, 73, 69, 83, 80, 84, 87, 65, 83, 88, 91, 69, 29, 4, 6,
86, 92, 69, 15, 24, 12, 27, 24, 69, 28, 21, 21, 29, 30, 1, 11, 80, 10, 22, 80,
17, 16, 21, 69, 9, 5, 4, 28, 2, 4, 12, 5, 23, 29, 80, 10, 30, 80, 17, 16,
21, 69, 27, 25, 23, 27, 28, 0, 84, 80, 22, 23, 80, 17, 16, 17, 17, 88, 25, 3,
88, 4, 13, 29, 80, 17, 10, 5, 0, 88, 3, 16, 21, 80, 10, 30, 80, 17, 16, 25,
22, 88, 3, 0, 10, 25, 0, 11, 80, 12, 11, 80, 10, 26, 4, 4, 17, 30, 0, 28,
92, 69, 30, 2, 10, 21, 80, 12, 12, 80, 4, 12, 80, 10, 22, 19, 0, 88, 4, 13,
29, 80, 20, 13, 17, 1, 10, 17, 17, 13, 2, 0, 88, 31, 3, 88, 4, 13, 29, 80,
6, 17, 2, 6, 20, 21, 69, 30, 31, 9, 20, 31, 18, 11, 94, 69, 54, 17, 8, 29,
28, 28, 84, 80, 44, 88, 24, 4, 14, 21, 69, 30, 31, 16, 22, 20, 69, 12, 24, 4,
12, 80, 17, 16, 21, 69, 11, 5, 8, 88, 31, 3, 88, 4, 13, 17, 3, 69, 11, 21,
23, 17, 21, 22, 88, 25, 22, 88, 17, 69, 11, 25, 29, 12, 24, 69, 8, 17, 23, 12,
80, 10, 30, 80, 17, 16, 21, 69, 11, 1, 16, 25, 2, 0, 88, 31, 3, 88, 4, 13,
29, 80, 21, 29, 2, 12, 21, 21, 17, 29, 2, 69, 23, 22, 69, 12, 24, 0, 88, 19,
12, 10, 19, 9, 29, 80, 18, 16, 31, 22, 29, 80, 1, 17, 17, 8, 29, 4, 0, 10,
80, 12, 11, 80, 84, 67, 80, 10, 10, 80, 7, 1, 80, 21, 13, 4, 17, 17, 30, 2,
88, 4, 13, 29, 80, 22, 13, 29, 69, 23, 22, 69, 12, 24, 12, 11, 80, 22, 29, 2,
12, 29, 3, 69, 29, 1, 16, 25, 28, 69, 12, 31, 69, 11, 92, 69, 17, 4, 69, 16,
17, 22, 88, 4, 13, 29, 80, 23, 25, 4, 12, 23, 80, 22, 9, 2, 17, 80, 70, 76,
88, 29, 16, 20, 4, 12, 8, 28, 12, 29, 20, 69, 26, 9, 69, 11, 80, 17, 23, 80,
84, 88, 31, 3, 88, 4, 13, 29, 80, 21, 29, 2, 12, 21, 21, 17, 29, 2, 69, 12,
31, 69, 12, 24, 0, 88, 20, 12, 25, 29, 0, 12, 21, 23, 86, 80, 44, 88, 7, 12,
20, 28, 69, 11, 31, 10, 22, 80, 22, 16, 31, 18, 88, 4, 13, 25, 4, 69, 12, 24,
0, 88, 3, 16, 21, 80, 10, 30, 80, 17, 16, 25, 22, 88, 3, 0, 10, 25, 0, 11,
80, 17, 23, 80, 7, 29, 80, 4, 8, 0, 23, 23, 8, 12, 21, 17, 17, 29, 28, 28,
88, 65, 75, 78, 68, 81, 65, 67, 81, 72, 70, 83, 64, 68, 87, 74, 70, 81, 75, 70,
81, 67, 80, 4, 22, 20, 69, 30, 2, 10, 21, 80, 8, 13, 28, 17, 17, 0, 9, 1,
25, 11, 31, 80, 17, 16, 25, 22, 88, 30, 16, 21, 18, 0, 10, 80, 7, 1, 80, 22,
17, 8, 73, 88, 17, 11, 28, 80, 17, 16, 21, 11, 88, 4, 4, 19, 25, 11, 31, 80,
17, 16, 21, 69, 11, 1, 16, 25, 2, 0, 88, 2, 10, 23, 4, 73, 88, 4, 13, 29,
80, 11, 13, 29, 7, 29, 2, 69, 75, 94, 84, 76, 65, 80, 65, 66, 83, 77, 67, 80,
64, 73, 82, 65, 67, 87, 75, 72, 69, 17, 3, 69, 17, 30, 1, 29, 21, 1, 88, 0,
23, 23, 20, 16, 27, 21, 1, 84, 80, 18, 16, 25, 6, 16, 80, 0, 0, 0, 23, 29,
3, 22, 29, 3, 69, 12, 24, 0, 88, 0, 0, 10, 25, 8, 29, 4, 0, 10, 80, 10,
30, 80, 4, 88, 19, 12, 10, 19, 9, 29, 80, 18, 16, 31, 22, 29, 80, 1, 17, 17,
8, 29, 4, 0, 10, 80, 12, 11, 80, 84, 86, 80, 35, 23, 28, 9, 23, 7, 12, 22,
23, 69, 25, 23, 4, 17, 30, 69, 12, 24, 0, 88, 3, 4, 21, 21, 69, 11, 4, 0,
8, 3, 69, 26, 9, 69, 15, 24, 12, 27, 24, 69, 49, 80, 13, 25, 20, 69, 25, 2,
23, 17, 6, 0, 28, 80, 4, 12, 80, 17, 16, 25, 22, 88, 3, 16, 21, 92, 69, 49,
80, 13, 25, 6, 0, 88, 20, 12, 11, 19, 10, 14, 21, 23, 29, 20, 69, 12, 24, 4,
12, 80, 17, 16, 21, 69, 11, 5, 8, 88, 31, 3, 88, 4, 13, 29, 80, 22, 29, 2,
12, 29, 3, 69, 73, 80, 78, 88, 65, 74, 73, 70, 69, 83, 80, 84, 87, 72, 84, 88,
91, 69, 73, 95, 87, 77, 70, 69, 83, 80, 84, 87, 70, 87, 77, 80, 78, 88, 21, 17,
27, 94, 69, 25, 28, 22, 23, 80, 1, 29, 0, 0, 22, 20, 22, 88, 31, 11, 88, 4,
13, 29, 80, 20, 13, 17, 1, 10, 17, 17, 13, 2, 0, 88, 31, 3, 88, 4, 13, 29,
80, 6, 17, 2, 6, 20, 21, 75, 88, 62, 4, 21, 21, 9, 1, 92, 69, 12, 24, 0,
88, 3, 16, 21, 80, 10, 30, 80, 17, 16, 25, 22, 88, 29, 16, 20, 4, 12, 8, 28,
12, 29, 20, 69, 26, 9, 69, 65, 64, 69, 31, 25, 19, 29, 3, 69, 12, 24, 0, 88,
18, 12, 9, 5, 4, 28, 2, 4, 12, 21, 69, 80, 22, 10, 13, 2, 17, 16, 80, 21,
23, 7, 0, 10, 89, 69, 23, 22, 69, 12, 24, 0, 88, 19, 12, 10, 19, 16, 21, 22,
0, 10, 21, 11, 27, 21, 69, 23, 22, 69, 12, 24, 0, 88, 0, 0, 10, 25, 8, 29,
4, 0, 10, 80, 10, 30, 80, 4, 88, 19, 12, 10, 19, 9, 29, 80, 18, 16, 31, 22,
29, 80, 1, 17, 17, 8, 29, 4, 0, 10, 80, 12, 11, 80, 84, 86, 80, 36, 22, 20,
69, 26, 9, 69, 11, 25, 8, 17, 28, 4, 10, 80, 23, 29, 17, 22, 23, 30, 12, 22,
23, 69, 49, 80, 13, 25, 6, 0, 88, 28, 12, 19, 21, 18, 17, 3, 0, 88, 18, 0,
29, 30, 69, 25, 18, 9, 29, 80, 17, 23, 80, 1, 29, 4, 0, 10, 29, 12, 22, 21,
69, 12, 24, 0, 88, 3, 16, 21, 3, 69, 23, 22, 69, 12, 24, 0, 88, 3, 16, 26,
3, 0, 9, 5, 0, 22, 4, 69, 11, 21, 23, 17, 21, 22, 88, 25, 11, 88, 7, 13,
17, 19, 13, 88, 4, 13, 29, 80, 0, 0, 0, 10, 22, 21, 11, 12, 3, 69, 25, 2,
0, 88, 21, 19, 29, 30, 69, 22, 5, 8, 26, 21, 23, 11, 94,
]
if __name__ == "__main__":
print(compute())

174
projecteuler/060/main.cpp Normal file
View File

@@ -0,0 +1,174 @@
/*
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
*/
#include <iostream>
#include <chrono>
#include <vector>
#include <unordered_set>
#include <cmath>
using namespace std;
vector<unsigned int> sieve(int n){
if(n < 2) return vector<unsigned int>();
vector<bool> ns(n, true);
for(int i = 2; i <= sqrt(n); ++i){
if(ns[i]){
int j = pow(i, 2);
while(j < n){
ns[j] = false;
j += i;
}
}
}
vector<unsigned int> primes;
for(size_t i = 2; i < ns.size(); ++i){
if(ns[i]) primes.push_back(i);
}
return primes;
}
// Wheel factorization primality test
bool isPrime(const unsigned long long n){
if(n % 2 == 0 || n % 3 == 0 || n % 5 == 0){
return n == 2 || n == 3 || n == 5;
}
const unsigned int delta[] = {6, 4, 2, 4, 2, 4, 6, 2};
unsigned long long i = 7;
int pos = 1;
while(i*i <= n){
if(n % i == 0){
return false;
}
i += delta[pos];
pos = (pos + 1) & 7;
}
return n > 1;
}
int intLength(const unsigned long long n){
return trunc(log10(n)) + 1;
}
unsigned long long combine(const unsigned long long n, const unsigned long long m){
unsigned long long res = n;
int mLength = intLength(m);
res *= pow(10, mLength);
res += m;
return res;
}
bool match(unsigned long long n, unsigned long long m){
return isPrime(combine(n, m)) && isPrime(combine(m, n));
}
// Assume that the size of all unordered sets is equal, otherwise this doesn't work
// WARNING: this is not an efficient function and it might even be bugged
vector<unordered_set<unsigned int>> aPriori(const vector<unordered_set<unsigned int>> & primePairs, const unordered_set<unsigned int> & primes){
if(primePairs.empty()) return vector<unordered_set<unsigned int>>();
int setSize = primePairs[0].size();
vector<unordered_set<unsigned int>> result;
for(size_t i = 0; i < primePairs.size(); ++i){
for(size_t j = min(i + 1, primePairs.size() - 1); j < primePairs.size(); ++j){
unordered_set<unsigned int> combinationSet(primePairs[i]);
for(int k : primePairs[j]){
combinationSet.insert(k);
}
if(combinationSet.size() == setSize + 1){
bool allPrimes = true;
for(auto it = combinationSet.begin(); it != combinationSet.end(); ++it){
for(auto jt = combinationSet.begin(); jt != combinationSet.end(); ++jt){
if(it != jt){
int p1 = combine(*it, *jt), p2 = combine(*jt, *it);
if(primes.find(p1) == primes.end() || primes.find(p2) == primes.end()){
allPrimes = false;
break;
}
}
}
}
if(allPrimes) result.push_back(combinationSet);
}
}
}
return result;
}
int main(){
std::cout << "Hello this is Patrick" << endl;
auto start = chrono::high_resolution_clock::now();
auto primeVector = sieve(10000);
// unordered_set<unsigned int> primes(primeVector.begin(), primeVector.end());
bool foundSum = false;
for(auto it = primeVector.begin(); it != primeVector.end(); ++it){
if(foundSum) break;
vector<int> candidateDoubles(it + 1, primeVector.end());
for(auto jt = candidateDoubles.begin(); jt != candidateDoubles.end(); ++jt){
if(foundSum) break;
if(match(*it, *jt)){
vector<int> candidateTriples(jt + 1, candidateDoubles.end());
for(auto kt = candidateTriples.begin(); kt != candidateTriples.end(); ++kt){
if(foundSum) break;
if(match(*it, *kt) && match(*jt, *kt)){
vector<int> candidateQuartets(kt + 1, candidateTriples.end());
for(auto lt = candidateQuartets.begin(); lt != candidateQuartets.end(); ++lt){
if(foundSum) break;
if(match(*it, *lt) && match(*jt, *lt) && match(*kt, *lt)){
vector<int> candidateQuintets(lt + 1, candidateQuartets.end());
for(auto mt = candidateQuintets.begin(); mt != candidateQuintets.end(); ++mt){
if(match(*it, *mt) && match(*jt, *mt) && match(*kt, *mt) && match(*lt, *mt)){
std::cout << *it << " " << *jt << " " << *kt << " " << *lt << " " << *mt << " equals: " << *it + *jt + *kt + *lt + *mt << endl;
foundSum = true;
break;
}
}
// For checking the result of four
// cout << *it << " " << *jt << " " << *kt << " " << *lt << endl;
}
}
}
}
}
}
}
auto duration = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
std::cout << (float)duration.count()/1000 << endl;
return 0;
}

154
projecteuler/061/main.cpp Normal file
View File

@@ -0,0 +1,154 @@
/*
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:
Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
Square P4,n=n2 1, 4, 9, 16, 25, ...
Pentagonal P5,n=n(3n1)/2 1, 5, 12, 22, 35, ...
Hexagonal P6,n=n(2n1) 1, 6, 15, 28, 45, ...
Heptagonal P7,n=n(5n3)/2 1, 7, 18, 34, 55, ...
Octagonal P8,n=n(3n2) 1, 8, 21, 40, 65, ...
The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties.
The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set.
This is the only set of 4-digit numbers with this property.
Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
*/
#include <iostream>
#include <chrono>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
uint triangle(uint n){
return n * (n + 1) / 2;
}
uint square(uint n){
return n * n;
}
uint pentagonal(uint n){
return n * (3 * n - 1) / 2;
}
uint hexagonal(uint n){
return n * (2 * n - 1);
}
uint heptagonal(uint n){
return n * (5 * n - 3) / 2;
}
uint octogonal(uint n){
return n * (3 * n - 2);
}
bool validEnd(uint n){
return n % 100 >= 10;
}
std::set<unsigned int> results;
const unsigned int Limit = 10000;
std::vector<unsigned int> all(Limit, 0);
uint finalMask = 0b111111000;
void fillVector(vector<uint> & toFill, const uint bitmask, uint (*calc)(uint n)){
uint value = calc(0);
for(uint i = 0; value < 10000; ++i){
if(value >= 1000 && validEnd(value)){
toFill[value] |= bitmask & finalMask;
}
value = calc(i + 1);
}
}
void search(vector<uint> & sequence, uint mask = 0){
unsigned int from = 1000;
unsigned int to = 10000;
if(!sequence.empty()){
auto lowerTwoDigits = sequence.back() % 100;
from = lowerTwoDigits * 100;
to = from + 100;
}
for(auto next = from; next < to; ++next){
auto categories = all[next];
if(categories == 0){
continue;
}
bool isUnique = true;
for(auto x : sequence){
if(x == next){
isUnique = false;
break;
}
if(!isUnique){
continue;
}
for(auto j = 3; j <=8; ++j){
auto thisCategory = 1 << j;
if((categories && thisCategory) == 0){
continue;
}
if((mask & thisCategory) != 0){
continue;
}
auto nextMask = mask | thisCategory;
if(nextMask == finalMask){
auto first = sequence.front();
auto lowerTwoDigits = next % 100;
auto upperTwoDigits = first / 100;
if(lowerTwoDigits == upperTwoDigits){
auto sum = next;
for(auto x : sequence){
sum += x;
}
results.insert(sum);
}
}
else{
sequence.push_back(next);
search(sequence, nextMask);
sequence.pop_back();
}
}
}
}
}
int main(){
cout << "Hello this is Patrick" << endl;
auto start = chrono::high_resolution_clock::now();
// Finally learned what exactly it means when 1 << n, which is nice
fillVector(all, 1 << 3, triangle);
fillVector(all, 1 << 4, square);
fillVector(all, 1 << 5, pentagonal);
fillVector(all, 1 << 6, hexagonal);
fillVector(all, 1 << 7, heptagonal);
fillVector(all, 1 << 8, octogonal);
vector<uint> sequence;
search(sequence);
for(auto x : results){
cout << x << endl;
}
auto duration = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
cout << (float)duration.count()/1000 << endl;
return 0;
}

33
projecteuler/063/main.cpp Normal file
View File

@@ -0,0 +1,33 @@
#include <iostream>
#include <chrono>
#include <cmath>
using namespace std;
uint intlength(long double i){
return floor(log10(i)) + 1;
}
int main(){
cout << "Hello this is Patrick" << endl;
auto start = chrono::high_resolution_clock::now();
int result = 0;
for(uint i = 1; i < 10; ++i){
for(uint j = 1; j <= 10000; ++j){
long double exp = pow(i, j);
if(intlength(exp) == j){
result++;
cout << i << " " << j << " " << exp << endl;
}
}
}
cout << result << endl;
auto duration = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
cout << (float)duration.count()/1000 << endl;
return 0;
}

View File

@@ -0,0 +1,21 @@
cmake_minimum_required(VERSION 3.1)
# C++ 11 is standard
set(CMAKE_CXX_STANDARD 11 CACHE STRING "The C++ standard to use")
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "-Wall")
project(
ProjectEuler
VERSION 0.0.1
LANGUAGES CXX
)
add_executable(base base.cpp)
# For each euler problem a new executable here
add_executable(euler059 059/main.cpp)
add_executable(euler060 060/main.cpp)
add_executable(euler061 061/main.cpp)
add_executable(euler063 063/main.cpp)

21
projecteuler/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3
projecteuler/README.md Normal file
View File

@@ -0,0 +1,3 @@
# project-euler
My personal (usually not optimized) solutions for the Project Euler challenges

16
projecteuler/base.cpp Normal file
View File

@@ -0,0 +1,16 @@
#include <iostream>
#include <chrono>
using namespace std;
int main(){
cout << "Hello this is Patrick" << endl;
auto start = chrono::high_resolution_clock::now();
// Insert code here
auto duration = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
cout << (float)duration.count()/1000 << endl;
return 0;
}

10
projecteuler/base.py Normal file
View File

@@ -0,0 +1,10 @@
import time
import math
def main():
print("Hello, this is Patrick")
t0 = time.time()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1 @@
36,22,80,0,0,4,23,25,19,17,88,4,4,19,21,11,88,22,23,23,29,69,12,24,0,88,25,11,12,2,10,28,5,6,12,25,10,22,80,10,30,80,10,22,21,69,23,22,69,61,5,9,29,2,66,11,80,8,23,3,17,88,19,0,20,21,7,10,17,17,29,20,69,8,17,21,29,2,22,84,80,71,60,21,69,11,5,8,21,25,22,88,3,0,10,25,0,10,5,8,88,2,0,27,25,21,10,31,6,25,2,16,21,82,69,35,63,11,88,4,13,29,80,22,13,29,22,88,31,3,88,3,0,10,25,0,11,80,10,30,80,23,29,19,12,8,2,10,27,17,9,11,45,95,88,57,69,16,17,19,29,80,23,29,19,0,22,4,9,1,80,3,23,5,11,28,92,69,9,5,12,12,21,69,13,30,0,0,0,0,27,4,0,28,28,28,84,80,4,22,80,0,20,21,2,25,30,17,88,21,29,8,2,0,11,3,12,23,30,69,30,31,23,88,4,13,29,80,0,22,4,12,10,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,65,69,83,80,84,87,68,69,83,80,84,87,73,69,83,80,84,87,65,83,88,91,69,29,4,6,86,92,69,15,24,12,27,24,69,28,21,21,29,30,1,11,80,10,22,80,17,16,21,69,9,5,4,28,2,4,12,5,23,29,80,10,30,80,17,16,21,69,27,25,23,27,28,0,84,80,22,23,80,17,16,17,17,88,25,3,88,4,13,29,80,17,10,5,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,12,11,80,10,26,4,4,17,30,0,28,92,69,30,2,10,21,80,12,12,80,4,12,80,10,22,19,0,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,69,30,31,9,20,31,18,11,94,69,54,17,8,29,28,28,84,80,44,88,24,4,14,21,69,30,31,16,22,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,25,22,88,17,69,11,25,29,12,24,69,8,17,23,12,80,10,30,80,17,16,21,69,11,1,16,25,2,0,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,23,22,69,12,24,0,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,67,80,10,10,80,7,1,80,21,13,4,17,17,30,2,88,4,13,29,80,22,13,29,69,23,22,69,12,24,12,11,80,22,29,2,12,29,3,69,29,1,16,25,28,69,12,31,69,11,92,69,17,4,69,16,17,22,88,4,13,29,80,23,25,4,12,23,80,22,9,2,17,80,70,76,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,11,80,17,23,80,84,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,12,31,69,12,24,0,88,20,12,25,29,0,12,21,23,86,80,44,88,7,12,20,28,69,11,31,10,22,80,22,16,31,18,88,4,13,25,4,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,17,23,80,7,29,80,4,8,0,23,23,8,12,21,17,17,29,28,28,88,65,75,78,68,81,65,67,81,72,70,83,64,68,87,74,70,81,75,70,81,67,80,4,22,20,69,30,2,10,21,80,8,13,28,17,17,0,9,1,25,11,31,80,17,16,25,22,88,30,16,21,18,0,10,80,7,1,80,22,17,8,73,88,17,11,28,80,17,16,21,11,88,4,4,19,25,11,31,80,17,16,21,69,11,1,16,25,2,0,88,2,10,23,4,73,88,4,13,29,80,11,13,29,7,29,2,69,75,94,84,76,65,80,65,66,83,77,67,80,64,73,82,65,67,87,75,72,69,17,3,69,17,30,1,29,21,1,88,0,23,23,20,16,27,21,1,84,80,18,16,25,6,16,80,0,0,0,23,29,3,22,29,3,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,35,23,28,9,23,7,12,22,23,69,25,23,4,17,30,69,12,24,0,88,3,4,21,21,69,11,4,0,8,3,69,26,9,69,15,24,12,27,24,69,49,80,13,25,20,69,25,2,23,17,6,0,28,80,4,12,80,17,16,25,22,88,3,16,21,92,69,49,80,13,25,6,0,88,20,12,11,19,10,14,21,23,29,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,29,80,22,29,2,12,29,3,69,73,80,78,88,65,74,73,70,69,83,80,84,87,72,84,88,91,69,73,95,87,77,70,69,83,80,84,87,70,87,77,80,78,88,21,17,27,94,69,25,28,22,23,80,1,29,0,0,22,20,22,88,31,11,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,75,88,62,4,21,21,9,1,92,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,65,64,69,31,25,19,29,3,69,12,24,0,88,18,12,9,5,4,28,2,4,12,21,69,80,22,10,13,2,17,16,80,21,23,7,0,10,89,69,23,22,69,12,24,0,88,19,12,10,19,16,21,22,0,10,21,11,27,21,69,23,22,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,36,22,20,69,26,9,69,11,25,8,17,28,4,10,80,23,29,17,22,23,30,12,22,23,69,49,80,13,25,6,0,88,28,12,19,21,18,17,3,0,88,18,0,29,30,69,25,18,9,29,80,17,23,80,1,29,4,0,10,29,12,22,21,69,12,24,0,88,3,16,21,3,69,23,22,69,12,24,0,88,3,16,26,3,0,9,5,0,22,4,69,11,21,23,17,21,22,88,25,11,88,7,13,17,19,13,88,4,13,29,80,0,0,0,10,22,21,11,12,3,69,25,2,0,88,21,19,29,30,69,22,5,8,26,21,23,11,94