#! /usr/bin/env python # -*- coding: utf-8; mode: python -*- """ Project Euler solutions. I was trying to solve at least one problem a day: https://projecteuler.net/profile/Naereen.png More informations online: - https://projecteuler.net/progress - https://projecteuler.net/archives - https://projecteuler.net/account @date: Thu Feb 19 12:06:42 2015. @author: Lilian Besson for CS101 course at Mahindra Ecole Centrale 2015. @licence: GNU Public License version 3. """ # %% Problem 1 # print "Problem 1 :", sum(filter(lambda n: (n % 3 == 0) or (n % 5 == 0), xrange(1, 1000))) currentSum = 0 for i in range(1, 1000): if (i % 3 == 0) or (i % 5 == 0): currentSum += i print("Problem 1 :", currentSum) # %% Problem 2 fmax = 4e6 fibs = [1, 2] i = 1 while fibs[i] < fmax: fibs.append(fibs[i- 1] + fibs[i]) i += 1 print("Problem 2 :", sum([f for f in fibs if (f < fmax) and (f % 2 == 0)])) # %% Problem 3 divides = lambda k, n: n% k == 0 # WARNING: not tail recursive! def primeFactors(n): if divides(2, n): return [2] + primeFactors(n / 2) k = 3 while (not divides(k, n)) and (k <= n): k += 2 # odd numbers only if divides(k, n): return [k] + primeFactors(n / k) elif n > 1: return [n] else: return [] def largestPrimeFactor(n): return max(primeFactors(n)) print("Problem 3 :", largestPrimeFactor(600851475143)) # %% Problem 4 from math import log, ceil def isPalindrom(n): decompo = [] for i in range(1, 1+ int(ceil(log(n, 10)))): decompo.append(n % 10) n = (n - (n % 10)) / 10 revDecompo = list(decompo) revDecompo.reverse() return decompo == revDecompo def maxPalindrom(nmax=1000): maxp = 1 x0, y0 = 1, 1 for x in range(1, nmax): for y in range(1, nmax): if isPalindrom(x * y) and x*y > maxp: maxp = x * y x0, y0 = x, y return maxp, x0, y0 print("Problem 4 :", maxPalindrom(100)[0]) print("Problem 4 :", maxPalindrom(1000)[0]) # %% Problem 5 def isEvenlyDivisible(n, k): return all([n% i == 0 for i in range(1, k+ 1)]) def minEvenlyDivisible(k): n = 1 while not isEvenlyDivisible(n, k): n += 1 return n print("Problem 5 :", minEvenlyDivisible(10)) print("Problem 5 :", minEvenlyDivisible(20)) # %% Problem 6 def sumIntegers(n): return n*(n+ 1)/2 def sumSquares(n): return n*(n+ 1)*(2*n+ 1)/6 print("Problem 6 :", sumIntegers(10)**2 - sumSquares(10)) print("Problem 6 :", sumIntegers(100)**2 - sumSquares(100)) # %% Problem 7 def isPrime(n): """ Basic implementation with a for and if loops, and break construct.""" result = True for k in range(2, int(math.sqrt(n))+ 1): if (n % k) == 0: # k is a divisor of n ==> n is not prime! result = False break # Exit the for loop right now return result nbprime = 10001 i = 3 nb = 2 # As long as we do not have enough prime numbers while nb < nbprime: # print i, "is the", nb, "th prime number." i += 2 while not isPrime(i): i += 2 nb += 1 print("Problem 7 :", i, "is the last (the", nb, "th one) prime number of our list.") # %% Problem 8 # Let us work with a string and not an integer : it is simpler to access s = """7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450""" def prod(l): p = 1 for x in l: p *= x return p def adjacentNumbers(s, k=4): lenS = len(s) index = 0 currentProd = 0 adjNbs = [] while index < lenS - k: adjNbs_x = [int(s[index+ i]) for i in range(0, k)] prod_x = prod(adjNbs_x) if currentProd < prod_x: adjNbs = adjNbs_x currentProd = prod_x index += 1 return adjNbs print("Problem 8 :", prod(adjacentNumbers(s, k=4))) print("Problem 8 :", prod(adjacentNumbers(s, k=13))) # %% Problem 9 n = 1000 bests = [3, 4, 5] for a in range(1, n- 1): for b in range(a+ 1, n- 1): c = n - (a+ b) if a**2 + b**2 == c**2: bests = [a, b, c] print("Problem 9 :", bests) print("Problem 9 :", bests[0] * bests[1] * bests[2]) # %% Problem 10 def isPrime(n): """ Basic implementation with a for and if loops, and break construct.""" result = True for k in range(2, int(math.sqrt(n))+ 1): if (n % k) == 0: # k is a divisor of n ==> n is not prime! result = False break # Exit the for loop right now return result N = 2000000 # N = 10 n = 3 sumOfPrimes = 2 while n < N: while not isPrime(n): n += 2 if isPrime(n): sumOfPrimes += n print("I am adding the prime number", n, "to the sum. Currently it is", sumOfPrimes) n += 2 print("Problem 10 :", sumOfPrimes) # %% Problem 11 grid2020 = """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 prod(l): p = 1 for x in l: p *= x return p def findGreatestProduct(s, k=4): size = 20 greatestProduct = -1 elementsOfProduct = [] besti, bestj = 0, 0 bestdirection = "Nope" for i in range(0, size - k + 1): for j in range(0, size): print("i is", i, "and j is", j) # Direction left/right elementsOfProduct_x = [int(s[3*(i + size*j + t):][0:2]) for t in range(0, k)] print("Direction left to right", elementsOfProduct_x) prod_x = prod(elementsOfProduct_x) if greatestProduct < prod_x: elementsOfProduct = elementsOfProduct_x greatestProduct = prod_x bestdirection = "left to right" besti, bestj = i, j for i in range(0, size): for j in range(0, size - k + 1): print("i is", i, "and j is", j) # Direction up/down elementsOfProduct_x = [int(s[3*(i + size*j + size*t):][0:2]) for t in range(0, k)] print("Direction up to down", elementsOfProduct_x) prod_x = prod(elementsOfProduct_x) if greatestProduct < prod_x: elementsOfProduct = elementsOfProduct_x greatestProduct = prod_x bestdirection = "up to down" besti, bestj = i, j for i in range(0, size - k + 1): for j in range(0, size - k + 1): print("i is", i, "and j is", j) # Direction diagonal y=x elementsOfProduct_x = [int(s[3*(i + size*j + (size+ 1)*t ):][0:2]) for t in range(0, k)] print("Direction diagonal y=x", elementsOfProduct_x) prod_x = prod(elementsOfProduct_x) if greatestProduct < prod_x: elementsOfProduct = elementsOfProduct_x greatestProduct = prod_x bestdirection = "y=x" besti, bestj = i, j for i in range(k, size): for j in range(0, size - k + 1): print("i is", i, "and j is", j) # Direction diagonal y=- x elementsOfProduct_x = [int(s[3*(i + size*j + (size- 1)*t ):][0:2]) for t in range(0, k)] print("Direction diagonal y=- x", elementsOfProduct_x) prod_x = prod(elementsOfProduct_x) if greatestProduct < prod_x: elementsOfProduct = elementsOfProduct_x greatestProduct = prod_x bestdirection = "y=- x" besti, bestj = i, j print("\n\nFinally, I found the best product to be", greatestProduct) print("For the direction", bestdirection) print("Starting from the i, j =", besti, ",", bestj) print("With the", k, "values", elementsOfProduct) return elementsOfProduct print("Problem 11 :", prod(findGreatestProduct(grid2020, k=1))) print("Problem 11 :", prod(findGreatestProduct(grid2020, k=4))) # %% Problem 12 # TODO conclude : need to be MORE EFFICIENT # divisors = lambda k: filter(lambda i: k% i == 0, xrange(1, k+ 1)) # nbDivisors = lambda k: sum(map(lambda i: i>0, divisors(k))) def nbDivisors(k): nb = 0 d = 1 while d <= k: while k% d != 0: d += 1 nb += 1 d += 1 return nb # Pour le problème, voici mes résultats théoriques : on appelle t(n) le nombre de diviseurs de n # # Si a et b sont premiers entre eux, t(ab)=t(a)t(b) # # Si a est pair, t(a/2)=v(a)/(v(a)+ 1)*t(a) # la valuation dyadique (la plus grande puissance de 2 divisant a) # # En particulier, t(a/2) est supérieur ou égal à t(a)/2 # donc si tu veux t(n(n+ 1)/2) supérieur à 500, tu obtiens t(n)t(n+ 1) supérieur à 1000 # de sorte qu'on peut regarder des n pour lesquels t(n) est environ 31 # Après il faut faire l'algo, je regarderai ça plus tard, c'était juste pour te donner mes résultats si jamais tu veux revenir sur le problème. def minTriangularNumberWithEnoughDivisor(minNbDivisor=5, startingN=1): n = startingN t = startingN * (startingN + 1) / 2 nbd = nbDivisors(t) while nbd < minNbDivisor: print("Still trying the next triangle number... n =", n, "and so t_n =", t, "with", nbd, "divisors") n += 1 t += n nbd = nbDivisors(t) print("I found the good triangle number: for n =", n, "and so t_n =", t, "with", nbd, "divisors") return t # print "Problem 12 : the value of the first triangle number to have over five divisors is", minTriangularNumberWithEnoughDivisor(5) # print "Problem 12 : the value of the first triangle number to have over one hundred divisors is", minTriangularNumberWithEnoughDivisor(100) print("Problem 12 : the value of the first triangle number to have over five hundred divisors is", minTriangularNumberWithEnoughDivisor(500, startingN=6533)) # FIXME too long! # %% Problem 13 nums = """ 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 """.replace('\n', '') partialSum = 0 for i in range(0, 100): sliceNum = nums[50*i:50*(i+ 1)] # print "The current sum is", partialSum print("The", i, "th 50-digit number is", sliceNum) partialSum += int(sliceNum) print("Problem 13 : the first ten digits of the sum of the following one-hundred 50-digit numbers is :", int((str(partialSum))[0:10])) # %% Problem 14 def nextCollatz(n): if n% 2 == 0: return n/2 else: return 3*n+ 1 def bestSeedForBiggerChain(maxn=10): bestSeed = 1 bigLength = 1 for seed in range(1, maxn): point = seed length = 1 while point != 1: point = nextCollatz(point) length += 1 if length > bigLength: bigLength = length bestSeed = seed return bestSeed, bigLength bestSeed, bigLength = bestSeedForBiggerChain(1000000) print("Problem 14 : the starting number under 1 million that produces the longest Collatz chain is", bestSeed, ": with a chain of length", bigLength) # %% Problem 15 global nbCall nbCall = [0] # Memoization table FIXME the function nbRoutes has sides effets, this dict should be initiliazed before each call memo = { (0, 0): 1, (0, 1): 1, (1, 1): 2 } def nbRoutes(x, y, acc = 0): """ Complexity (number of subcalls) is now sub-linear: less than x calls apparently !""" print("nbRoutes has been called with : x =", x, "and y =", y, "and acc =", acc) nbCall[0] += 1 # Optimization 1 : memoization if (x, y) in memo: print("The value nbRoutes({}, {}) has been computed already: I read it ({}) from the memoization table (of size {}).".format(x, y, memo[(x, y)], len(memo))) return memo[(x, y)] + acc # We use the intrinsec symetry of the problem if (y, x) in memo: print("The value nbRoutes({}, {}) has been computed already: I read it ({}) from the memoization table (of size {}).".format(y, x, memo[(y, x)], len(memo))) return memo[(y, x)] + acc # Basic case if x > 0 and y > 0: memo[(x, y)] = nbRoutes(x- 1, y, acc = acc + nbRoutes(x, y- 1)) - acc print("The value nbRoutes({}, {}) has been computed for the first time: I write it ({}) to the memoization table (now of size {}).".format(x, y, memo[(x, y)], len(memo))) return memo[(x, y)] + acc else: print("Producing 1 : I found one recursice call with x, y = 0, 0...") return 1 + acc # Too time consuming without memoization # def nbRoutes(x, y, acc=1): # print "x =", x, "and y =", y, "and acc =", acc # if x > 0 and y > 0: # return nbRoutes(x-1, y, acc=acc + nbRoutes(x, y-1)) # else: # return acc def solveProblem15(x, y): print("Problem 15 : starting to solve for a {x}×{y} grid (x = {x}, y = {y}).".format(x=x, y=y)) nbCall[0] = 0 # memo = { (0, 0): 1, (0, 1): 1, (1, 1): 2 } # memo = dict() # nb = nbRoutes(x, y) # BETTER solution: obvious in fact... from math import factorial nb = factorial(x+y)/(factorial(x)*factorial(y)) print("Problem 15 : through a {}×{} grid, there is {} such routes. I took {} recursive call(s) of nbRoutes.".format(x, y, nb, nbCall[0])) return nb assert 6 == solveProblem15(2, 2) # 6 assert 20 == solveProblem15(3, 3) # 20 solveProblem15(15, 15) # 155117520 solveProblem15(20, 20) # 137846528820 with 181 calls # solveProblem15(200, 200) # 102952500135414432972975880320401986757210925381077648234849059575923332372651958598336595518976492951564048597506774120 with 39781 calls # solveProblem15(500, 500) # 270288240945436569515614693625975275496152008446548287007392875106625428705522193898612483924502370165362606085021546104802209750050679917549894219699518475423665484263751733356162464079737887344364574161119497604571044985756287880514600994219426752366915856603136862602484428109296905863799821216320L with 210301 calls # %% Problem 16 pb16 = lambda n: sum([int(c) for c in str(2**n)]) print("Problem 16 : the power digit sum of 2**15 is", pb16(15)) print("Problem 16 : the power digit sum of 2**1000 is", pb16(1000)) # %% Problem 17 def num2english(num): """ Thanks to http://bytes.com/topic/python/answers/875129-number-string#post3517015""" numDict1 = {0: '', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety' } thousands, rem = divmod(num, 1000) hundreds, rem = divmod(rem, 100) tens, ones = divmod(rem, 10) output = "" if thousands>0: output += numDict1[thousands]+" thousand " if hundreds>0: output += numDict1[hundreds]+" hundred" if (hundreds>0 or thousands>0) and 10*tens+ones>0: output += " and " if tens>1: output += numDict1[10*tens] if ones>0: output += "-"+numDict1[ones] else: output += numDict1[10*tens+ones] # To get rid of trailing spaces that may be left, and remove spaces return output.strip() for i in range(1, 1001): print("The number i =", i, "is written as", num2english(i), "(so it has", len(num2english(i).replace(' ', '').replace('-', '')), "letters).") def numberOfLettersUsed(n = 5): list_of_strings = [num2english(i) for i in range(1, n+1) ] # print list_of_strings return sum([len(s.replace(' ', '').replace('-', '')) for s in list_of_strings]) def pb17(n): num = numberOfLettersUsed(n) print("Problem 17 : if all the numbers from 1 to", n, "inclusive were written out in words", num, "letters would be used.") pb17(5) pb17(1000) # for i in xrange(1, 1001): # pb17(i) # %% Problem 18 from math import ceil, log def decompo_base(n, base=10, size=None): assert n >= 0 if n == 0: return [0]*size else: decompo = list() for i in range(0, int(ceil(log(n, base)))): decompo.append(n % base) n = (n - (n % base)) / base decompo.reverse() if size: decompo = [0]*(size-len(decompo)) + decompo return decompo def sum_following_path(triangle, path, n): partialSum = 0 lines = triangle.splitlines() n = len(lines) j = 0 i = 0 while j < n: linej = lines[j].split() s = linej[i] partialSum += int(s) # print "On the line j =", j, "at index i =", i, "I read the string s =", s, ": now the partial sum is", partialSum if j >= n-1: break # Now we look at the next direction direction = path[j] i += direction # if 0 we chose left, 1 we chose right # if direction == 0: # print " going left" # elif direction == 1: # print " going right" j += 1 # Done return partialSum def max_total_triangle_greedy(triangle): lines = triangle.splitlines() n = len(lines) bestSum = 0 bestPath = [] for indexRoute in range(2**(n-1)): path = decompo_base(indexRoute, base=2, size=n-1) print("The", indexRoute, "th path is", path) currentSum = sum_following_path(triangle, path, n) if bestSum < currentSum: print("I found a better sum, of value", currentSum, "for the path", path) bestPath = path bestSum = currentSum return bestSum, bestPath def pb18(triangle): num = max_total_triangle_greedy(triangle) print("Problem 18 : By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is", num) triangle1 = """3 7 4 2 4 6 8 5 9 3""" pb18(triangle1) triangle2 = """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""" pb18(triangle2) # %% Problem 19 # TODO a terminer isLeap = lambda y: y%400 == 0 or (y%4 == 0 and y%100 != 0) # %% Problem 20 from math import factorial print("Problem 20 : Find the sum of the digits in the number 10! is", sum([ int(c) for c in str(factorial(10)) ])) print("Problem 20 : Find the sum of the digits in the number 100! is", sum([ int(c) for c in str(factorial(100)) ])) # %% Problem 21 divs = lambda k: [ i for i in range(1, int(k)) if int(k)%i == 0 ] d = lambda k: sum([ i for i in range(1, int(k)) if int(k)%i == 0 ]) print("220 and 284 are amicable numbers, because d(220), d(284) =", d(220), ",", d(284)) def sumOfAmicablesNumber(N = 10000): partialSum = 0 for a in range(1, N): b = d(a) if d(b) == a and a!=b: partialSum += a print("I found an amicable number: a =", a, "and b = d(a) =", d(a), "and d(b) = a.") return int(partialSum) sumAmis = sumOfAmicablesNumber() print("Problem 21 : the sum of all the amicable numbers under 10000 is", sumAmis) # print sum([ i for i in xrange(1, 10000) if d(d(i))==i and i!=d(i) ]) # %% Problem 22 alphaDict = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i]:1+i for i in range(26) } def valueOfChar(c): return alphaDict[c] def valueOfString(s): return sum([ valueOfChar(c) for c in s ]) with open("p022_names.txt") as f: line = f.readlines()[0] names = [ s.replace('"', '') for s in line.split(',') ] print("Problem 22 : the sum of the scores is:") names.sort() # print sum( [ (position+1) * valueOfString(name) for position, name in enumerate(names) ] ) score = 0 for position, name in enumerate(names): hisScore = (position+1) * valueOfString(name) print("For the", position, "name, being", name, "his score is", hisScore) score += hisScore # if name == 'COLIN': break # FIXME it was for testing print("So the total score is", score) # %% Problem 23 divs = lambda k: [ i for i in range(1, 1+int(k)/2) if int(k)%i == 0 ] isPerfect = lambda n: n == sum(divs(n)) isDeficient = lambda n: n > sum(divs(n)) # Dynamic programming to not compute again what we already know listAbundant = [] def isAbundant(n): if n in listAbundant: return True else: r = n < sum(divs(n)) if r: listAbundant.append(n) return r # sumCannotBeWrittenSumTwoAbundant = 4179871 sumCannotBeWrittenSumTwoAbundant = 0 for n in range(1, 28123 + 1, 2): # print "Trying to know if n = {} can be written as sum of two abundant numbers.".format(n) cannotBeWritten = True for x in range(2, 1+n/2): y = n - x # n = x + y # Now we check if x and y are abundant if isAbundant(x) and isAbundant(y): cannotBeWritten = False # print " I found x = {} and y = {}, two abundant numbers (indeed d(x) = {} and d(y) = {}), so I stop searching, and do not add n to the sum.".format(x, y, sum(divs(x)), sum(divs(y))) break if cannotBeWritten: sumCannotBeWrittenSumTwoAbundant += n print("n = {} is being added to the sum, which is currently {}.".format(n, sumCannotBeWrittenSumTwoAbundant)) print("For numbers below 28123, the sum is", sumCannotBeWrittenSumTwoAbundant) # %% Problem 24 # TODO # %% Problem 25 from math import log, ceil N = 1000 fib, fibnext = [1, 1] n = 1 while ceil(log(fib, 10)) < N: fib, fibnext = fibnext, fib + fibnext n += 1 print("Problem 25 : n =", n, "is the smallest n>0 such that F_n =", fib ,"the nth Fibonacci number has more than", N, "digits.") # %% Problem 24 goodOne = None from itertools import permutation i = 0 for l in permutation(list(range(0, 10))): if i+1 == 1000000: goodOne = l break i += 1 print("Problem 24 : the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 is ", goodOne) # %% Problem 26 from decimal import * def recurring_cycle(d): precision = getcontext().prec frac_d = Decimal(1)/Decimal(d) s_d0 = str(frac_d)[2:] # remove the 0. in the beginning n = len(s_d0) # number of caracters if n < precision: print(d, "has a finite number of digits, so a length of recurring cycle of 0.") return 0 # d has a finite number of digits else: print("Starting to try with a recurring cycle of length = 1.") bests = {'length': 0, 'cycle': ''} for start in range(0, 1): print("Trying any cycle starting at position", start) s_d = s_d0[start:] n = len(s_d) length = 1 m = n - (n % length) # truncate while (s_d[:length])*(m / length) != s_d[:m]: print("The recurring cycle", s_d[:length], "starting from position", start, "and of length", length) # print "Concatenated", (m / length), "number of time" # print "is still not equal to", s_d[:m] # print "which is s_d of limited size", m length += 1 m = n - (n % length) # truncate # print "\nTrying with a recurring cycle of length =", length # End of the while loop if length > bests['length']: bests = {'length': length, 'cycle': s_d[start:start+length]} print("For the number 1/{}, we finally found a good recurring cycle {} of size {}.".format(d, bests['cycle'], bests['length'])) return bests['length'] def pb26(N = 1000): getcontext().prec = 10*N # TODO improve? best_d = 1 longest_recurring_cycle = 0 print("Looking for the value d < {} for which 1/d contains the longest recurring cycle in its decimal fraction part.".format(N)) for d in range(1, N): print("\n\nFor the candidate 1/d, with d =", d) r = recurring_cycle(d) if r > longest_recurring_cycle: longest_recurring_cycle, best_d = r, d print("\nProblem 26 : the value of d < {N} for which 1/d contains the longest recurring cycle in its decimal fraction part is {d} (with a cycle of size {size}).".format(N=N, d=best_d, size=longest_recurring_cycle)) pb26(N = 11) # pb26(N = 1000) # %% Problem 27 from sympy import isprime # quicker than my solution # Test the first formula assert all([ isprime(n**2 + n + 41) for n in range(40)]) # Test the second formula assert all([ isprime(n**2 - 79*n + 1601) for n in range(80)]) def number_of_consecutive_primes(a, b, n = 0): """ Returns the maximum number of consecutive primes generated by the quadratic expression n**2 + an + b.""" f = lambda n: n**2 + a*n + b while True: if not isprime(f(n)): return n n += 1 assert number_of_consecutive_primes(1, 41) == 40 assert number_of_consecutive_primes(-79, 1601) == 80 def pb27(A = 1000, B = 1000): max_number_of_consecutive_primes = 0 best_a, best_b = -A+1, -B+1 for a in range(-A+1, A): for b in range(-B+1, B): nb = number_of_consecutive_primes(a, b) if nb > max_number_of_consecutive_primes: max_number_of_consecutive_primes = nb best_a, best_b = a, b return best_a, best_b, max_number_of_consecutive_primes A, B = 1000, 1000 # FIXME change here a, b, maxnb = pb27(A, B) print("Problem 27 : the product of the coefficients, a and b (with 0 <= |a| < {A}, 0 <= |b| < {B}), for the quadratic expression (n² + an + b) that produces the maximum number of primes (being {maxnb}) for consecutive values of n (starting with n = 0) is {ab} (for a = {a} and b = {b}).".format(A=A, B=B, ab=a*b, a=a, b=b, maxnb=maxnb)) # %% Problem 28 def pb28(n): assert n%2 == 1 # these computations are only true for odd values of n # First diagonal : North-East sum1 = sum([ k**2 for k in range(1, n+1, 2) ]) print("For n= {n}, the sum for the NE diagonal is {s}.".format(n=n, s=sum1)) # Second diagonal : South-East sum2 = sum([ k**2 - k+1 for k in range(2, n+1, 2) ]) print("For n= {n}, the sum for the SE diagonal is {s}.".format(n=n, s=sum2)) # Third diagonal : South-West sum3 = sum([ k**2 + 1 for k in range(2, n+1, 2) ]) print("For n= {n}, the sum for the SW diagonal is {s}.".format(n=n, s=sum3)) # Forth diagonal : North-West sum4 = sum([ k**2 - k+1 for k in range(3, n+1, 2) ]) print("For n= {n}, the sum for the NW diagonal is {s}.".format(n=n, s=sum4)) return sum1 + sum2 + sum3 + sum4 assert pb28(5) == 101 print('\n') n = 1001 print("Problem 28 : the sum of the numbers on the diagonals in a {n} by {n} spiral formed in the same way is {s}.".format(n=n, s=pb28(n))) # 669171001 # %% Problem 29 n29 = len({ a**b for a in range(2, 101) for b in range(2, 101) }) print("Problem 29 : there is {} distinct term(s) in the sequence generated by a**b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100.".format(n29)) # %% Problem 30 def is_sum_of_powers_of_its_digits(N, k): return N == sum([ int(d)**k for d in str(N) ]) # assert all([is_sum_of_powers_of_its_digits(N, 4) for N in [1634, 8208, 9474] ]) assert is_sum_of_powers_of_its_digits(1634, 4) assert is_sum_of_powers_of_its_digits(8208, 4) assert is_sum_of_powers_of_its_digits(9474, 4) print("Problem 30 : the sum of all the numbers than are sum of their digits to the power 4 is :", sum([1634, 8208, 9474])) for i in range(10): print("{}**5 = {}".format(i, i**5)) n30_4 = sum([ n for n in range(2, 10000) if is_sum_of_powers_of_its_digits(n, 4) ]) print("Problem 30 : the (bounded) sum of all the numbers than are sum of their digits to the power 4 is :", n30_4) assert n30_4 == 19316 l30_5 = [ n for n in range(2, 200000) if is_sum_of_powers_of_its_digits(n, 5) ] print(l30_5) n30_5 = sum(l30_5) # 443839 print("Problem 30 : the (bounded) sum of all the numbers than are sum of their digits to the power 5 is :", n30_5) # %% Problem 31 list_coins_uk = [ 200, 100, 50, 20, 10, 5, 2, 1 ] list_coins_uk.sort(reverse=True) total = 200 # 200 def nways(n, coins): m = len(coins) ways = [ [0 for j in range(m+1)] for i in range(n+1) ] # initialize base cases for i in range(n+1): ways[i][0] = 0 for j in range(m+1): ways[0][j] = 1 for i in range(1, n+1): for j in range(1, m+1): ways[i][j] += ways[i][j-1] if i >= coins[j-1]: ways[i][j] += ways[i - coins[j-1]][j] return ways[n][m] n31 = nways(total, list_coins_uk) print("Problem 31 : for the coins", list_coins_uk, "and total of", total, "the number of possible combinations is", n31) # %% Problem 48 n48 = int(str(sum([ i**i for i in range(1, 1001) ]))[-10:]) print("Problem 48 : the last ten digits of the series 1**1 + 2**2 + 3**3 + ... + 1000**1000 is", n48)