Project Euler Problem #17:

Problem #17 is the first of many Project Euler problems that are very easy with certain libraries, but are painful to implement otherwise. Here is the question:

Project Euler Problem 17: Number letter counts
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

While this problem may sound simple, it would be quite annoying to implement. There are many, many cases that you have to consider, such as the way how the numbers 11-19 are converted to English differently than the numbers 21-29 or 31-39. As a result, this would be a very nasty problem to solve legitimately without external tools. Luckily, computer scientists have access to a massive variety of libraries that are built just to solve problems like this.

Solution #1: Library Approach

As it turns out, the Python library “inflect.py” comes with a number of functions that are made exactly for the purpose of converting numbers to English. Because implementing this problem would be nasty (plus I’m lazy), it is much easier to just import a library that can solve it for us. Here is a solution that utilizes the inflect Python library:

 '''
 Author: Walker Kroubalkian
 Library Approach to Project Euler Problem #17
 '''

 import inflect
 import time

 def countLetters(myString):
     total = 0
     for c in myString:
         if "a"<=c<="z":
             total+=1
     return total

 def projectEulerProblemSeventeen(n):
     total = 0
     i = inflect.engine()
     for x in range(1,(n+1)):
         total+=countLetters(i.number_to_words(x))
     return total

 start = time.time()
 print projectEulerProblemSeventeen(1000)
 print ("--- %s seconds ---" % (time.time()-start))

 '''
 Prints
 21124
 --- 0.0325779914856 seconds ---
 for input of n=1000
 '''

And without doing much work at all, we are done.

Thanks for reading!

Project Euler Problem #16:

Problem #16 is another example of how some problems are much simpler in certain languages than other languages, and like Problem #13, it is a possible contender for the simplest Project Euler question. The question reads:

Project Euler Problem 16: Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

Because 2^1000 is an integer, it makes sense to store its value in the “int” data type. Unfortunately, most programming languages only give “int” variables 32 bits, meaning that values greater than 2^31 will not be stored accurately. Luckily, this isn’t an issue in Python 2.7. Here is my solution to this problem:

Solution #1: Brute Force Approach

We simply store the value of 2^1000, convert it to a string, and then add up each digit in the string. Here is an implementation of this method in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Brute Force Approach to Project Euler Problem #16
 '''
 import time
 def projectEulerProblemSixteen(m,n):
     a = str(m**n)
     total = 0
     for c in a:
         total+=int(c)
     return total
 start = time.time()
 print projectEulerProblemSixteen(2, 1000)
 print ("--- %s seconds ---" % (time.time()-start))
 '''
 Prints
 1366
 --- 0.000135898590088 seconds ---
 for input of m=2, n=1000
 '''

Of course, if we were working in a different programming language, this would take a bit more work, such as casting 2^1000 as a long or something of that sort. Otherwise, this problem is quite simple.

That’s all for today. Thanks for reading!

Project Euler Problem #15:

Problem #15 is yet another example of how having a decent background in mathematics can give you a huge edge in tackling Project Euler. The question reads:

Project Euler Problem 15: Lattice paths
Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?

This type of problem has appeared so many times on introductory math competitions such as the AMC 10/12 and Mathcounts that most serious math students know its answer by heart. Having this knowledge results in the following solution:

Solution #1 : Basic Combinatorial Approach

The key observation here is that every path can be interpreted as a series of moves to the right and moves down. If we let a move to the right be an “R” and a move down be a “D”, then we can rewrite the paths in the diagram as RRDD, RDRD, RDDR, DRRD, DRDR, and DDRR. Every sequence with 2 R’s and 2D’s is represented in this list. Thus, there is a one-to-one correspondence between paths on an mxn grid and sequences of m R’s and n D’s. The number of such sequences is the same as the number of ways to choose the m spots for the R’s out of the m+n possibilities, as all of the remaining spots will automatically be filled by D’s. The order these positions are chosen does not matter as any two R’s or two D’s are indistinguishable. Thus, for an mxn grid the answer is (m+n) choose m.

At this point this problem is a simple matter of implementing a combinatorial function. Here is an implementation of this function in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Combinatorial Approach to Project Euler Problem #15
 '''

 import time

 def projectEulerProblemFifteen(r, c):
     total = 1
     for i in range(1,(c+1)):
         total*=(r+c+1-i)
         total/=i
     return total

 start = time.time()
 print projectEulerProblemFifteen(20, 20)
 print ("--- %s seconds ---" % (time.time()-start))

 '''
 Prints
 137846528820
 --- 1.50203704834e-05 seconds ---
 for input of r = 20, c = 20
 '''

As shown above, understanding combinations is a critical component of solving Project Euler problems. I believe this is the shortest solution in any of my posts so far.

Thanks for reading.

Project Euler Problem #14:

Problem #14 is the first of many Project Euler problems to feature the Collatz Sequence. The Collatz Sequence, named from the infamous Collatz Conjecture, is the sequence of numbers that follow an arbitrary starting integer “n” when the following process is performed: If x is the current number, whenever x is even, divide x by 2 to get the next term, otherwise, multiply x by 3 and add 1 to get the next term. The Collatz Conjecture is an unproved hypothesis that all possible starting values of n will ultimately produce the oscillating sequence 4, 2, 1, 4, 2, 1, . . .

Proving the Collatz conjecture is a notoriously difficult task that is far beyond the scope of any problem on Project Euler. The famous Hungarian mathematician Paul Erdos infamously stated that “Mathematics may not be ready for such problems” when discussing the Collatz conjecture. Luckily, we are not required to prove the Collatz conjecture in Problem #14. The problem reads:

Project Euler Problem 14: Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:

n -> n/2 (n is even)
n -> 3n+1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

I have a small confession to make about this problem. When I first attempted this problem, I couldn’t think of a way to do it without basic brute force. As a result, I solved it through means of brute force with a script that took about 11 seconds to run. Afterwards, I read Project Euler’s documentation on this problem and spoiled myself about a more efficient means of solving it. I will present the brute force solution first, and then Project Euler’s solution:

Solution #1: Brute Force Approach

My brute force approach to this problem is possibly the most brain-dead means of solving this problem. First I made a function that finds the length of the Collatz sequence for an arbitrary starting number. Then I calculated the length of the sequence for all starting values less than a million and stored a running maximum index and length. Once the process was complete, I had the starting term with the longest chain. Here is my implementation of this method in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Brute Force Approach to Project Euler Problem #14
 '''

 import time

 def getCollatzLength(x):
     t = 0
     while(x>1):
         if(x%2==0):
             x/=2
         else:
             x = 3*x+1
         t+=1
     return t

 def projectEulerProblemFourteen(x):
     maxIndex = -1
     maxLength = 0
     for i in range(1,x):
         a = getCollatzLength(i)
         if(a>maxLength):
             maxLength = a
             maxIndex = i
     return maxIndex

 start = time.time()
 print projectEulerProblemFourteen(1000000)
 print ("--- %s seconds ---" % (time.time()-start))

 '''
 Prints
 837799
 --- 11.196969986 seconds ---
 for input of n=1000000
 '''

As shown above, this solution does pass Project Euler’s “One Minute Rule”, but it is not very optimized. For example, by the time I calculate the length of the sequence for i = 600,000, I have already calculated the length of the sequence for i = 600,000/2 = 300,000 which should be 1 less. This algorithm does not pick up on that fact, and therefore it wastes a ton of time. There are many other inefficiencies in this algorithm that are corrected in Project Euler’s solution. Here is the solution from Project Euler’s documentation for this problem:

Solution #2: Dictionary Approach (Credits to PE)

Project Euler’s solution fixes two major inefficiencies with the brute force algorithm. First of all, it uses a dictionary to recursively store the length of the sequence for any intermediate value in a sequence we check. Secondly, it notices that the Collatz sequence for a starting value of 2n is always 1 greater than the Collatz sequence for a starting value of n, and therefore it is only necessary to check starting values greater than or equal to 500,000. Using these two observations, the solution becomes much more efficient. I have implemented Project Euler’s solution in Python 2.7:

 '''
 Author: Project Euler with Python Implementation by Walker Kroubalkian
 Dictionary Approach to Project Euler Problem #14
 '''

 import time

 def projectEulerProblemFourteen(n):
     longestLength = 0
     longestIndex = -1
     knownIndices = {1: 1}

     def indexLength(x):
         if x in knownIndices:
             return knownIndices.get(x)
         if(x%2==0):
             knownIndices[x] = indexLength(x/2)+1
         else:
             knownIndices[x] = indexLength(3*x+1)+1
         return knownIndices[x]

     for i in range(n/2,n):
         a = indexLength(i)
         if(a > longestLength):
             longestLength = a
             longestIndex = i

     return longestIndex

 start = time.time()
 print projectEulerProblemFourteen(1000000)
 print ("--- %s seconds ---" % (time.time()-start))
 '''
 Prints
 837799
 --- 1.09148907661 seconds ---
 for input of n=1000000
 '''

This solution was my first experience with Python dictionaries and functions within functions. Unfortunately, even with Project Euler’s improvements, my implementation in Python fails to solve this problem in under a second (I believe this is the first time among all of my blog posts). I would like to return to this problem to optimize it further.

Thanks for reading! See you tomorrow!

Project Euler Problem #13:

Problem #13 is a good contender for the most basic Project Euler problem, depending on what programming language you use. Like Problems 8 and 11, this problem involves analyzing a ridiculous amount of data. However, unlike those problems, the iteration this one requires you to do is so simple that it’s one of the first things anyone learns when beginning to program. The question reads:

Project Euler Problem 13: Large sum
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

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

Once you’ve read the problem statement, it should be pretty obvious how simple this is. Of course, some languages make this type of operation easier than others. It is natural to store integers in the “int” variable type in most programming languages, but most languages only give integer variables 32 bits, meaning that they cannot accurately store values greater than 2^31 – 1. Users who work in these languages will probably have to cast the data in other data types such as “long”.

Luckily, I have been working in Python 2.7 which allows integers to be pretty much as large as you want. Therefore, when working in Python this problem is about as simple as it seems. Here is the solution I found to this problem:

Solution #1: Basic Iteration Approach

Of course, as in Problems 8 and 11, I copy pasted the given numbers into a different file (which I called “PE13Numbers.txt”) and then read from that file with my Python script. After parsing all of the strings in that file as integers, it was a simple matter of iterating through the list and adding each number to a running total.

The only interesting part is returning the first ten digits. By “first ten digits”, Project Euler means the left-most ten digits. This means that we can’t just use the modulus operator to find these digits. Luckily, Python allows us to convert integers to strings, and obtaining substrings from those strings is quite easy. This allows us to quickly get the left-most ten digits from the sum. Here is an implementation of this method in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Basic Python Approach to Project Euler Problem #13
 '''

 import time

 f = open("PE13Numbers.txt","r")
 if f.mode=="r":
     contents = f.readlines()
     realContents = []
     for x in contents:
         realContents.append(int(x))
 else:
     raise ValueError("Cannot read from file")

 def projectEulerProblemThirteen(numbers, n):
     total = 0
     for x in numbers:
         total+=x
     return str(total)[0:n]

 start = time.time()
 print projectEulerProblemThirteen(realContents, 10)
 print ("--- %s seconds ---" % (time.time()-start))

 '''
 Prints
 5537376230
 --- 1.59740447998e-05 seconds ---
 for input of given numbers and n=10
 '''

Looking back at my earlier solutions, it turns out my solution to Problem #3 was actually shorter in length than this one. This is mostly because I had to spend several lines in this solution to read the lines from the file in this problem.

Thanks for reading. See you tomorrow for what will surely be a more complex problem.

Project Euler Problem #12:

Problem #12 is the first of many Project Euler problems to feature multiplicative functions. A multiplicative function is a function f such that for all natural numbers x and y such that gcd(x,y)=1, f(xy) = f(x) * f(y). One of the most common multiplicative functions is the Divisor Function, or the function which returns the number of divisors of a number. Understanding this function is crucial to solving this problem:

Project Euler Problem 12: Highly divisible triangular number
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1+2+3+4+5+6+7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, . . .

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1, 3
6: 1, 2, 3, 6
10: 1, 2, 5, 10
15: 1, 3, 5, 15
21: 1, 3, 7, 21
28: 1, 2, 4, 7, 14, 28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

A simplistic way of counting the divisors of a number is to iterate through all numbers from 1 to the number and count the numbers that divide evenly. A slightly better way is counting from 1 to the square root of the number and doubling the result (or adding 1 in the case of square numbers). However, the fastest method of counting the divisors of a number reveals that the Divisor Function is multiplicative: the number of divisors of a function is the product of the results when 1 is added to each exponent in the prime factorization of the number. Using this fact, we can quickly count the divisors of a number. This results in the following solution:

Solution #1: Brute Force Approach

As discussed in an earlier problem, the nth triangular number is n(n+1)/2. This number gets big quite fast, so it could be difficult to factor the triangular numbers as they get bigger. The key observation that circumvents this problem is that n is relatively prime to (n+1). Because of this, we know that if d(n) is the divisor function, then d(n(n+1)/2) = d(n/2)*d(n+1) if n is even or d(n(n+1)/2) = d(n)*d((n+1)/2) if n is odd. Thus, it is not necessary for us to count the divisors of each large triangular number. Instead we only need to count the divisors of each index for the triangular numbers and then multiply consecutive numbers of divisors until one product is greater than 500. Here is an implementation of this approach in Python 2.7:

'''
Author: Walker Kroubalkian
Brute Force Approach to Project Euler Problem #12
'''
import time
from math import sqrt
def numberDivisors(n):
    total = 1
    c = 2
    while(c<=sqrt(n)):
        if(n%c==0):
            t = 0
            while(n%c==0):
                n/=c
                t+=1
            total*=(t+1)
        c+=1
    if(n>1):
        total*=2
    return total

def projectEulerProblemTwelve(n):
    last = 1
    if(n==1):
        return 1
    c = 3
    while(True):
        if(c%2==0):
            a = numberDivisors(c/2)
        else:
            a = numberDivisors(c)
        if(a*last>n):
            return c*(c-1)/2
        last = a
        c+=1

start = time.time()
print projectEulerProblemTwelve(500)
print ("--- %s seconds ---" % (time.time()-start))
'''
Prints
76576500
--- 0.0434160232544 seconds ---
for input of n=500
'''

I am not thrilled with this solution as I believe it can be optimized with a different method. If it were possible to place an upper bound on the first number with a given number of factors, a sieve could be used to find the number of divisors of all numbers up to a given number. I may return to this question eventually.

That is all for today. I hope you enjoyed!

Project Euler Problem #11:

Problem #11, like Problem #8, is one of the many Project Euler problems that requires the user to analyze a large amount of data. Here is its statement:

Project Euler Problem 11: Largest product in a grid
In the 20 x 20 grid below, four numbers along a diagonal line have been marked in red. (bold in my blog post)

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

The product of these numbers is 26 x 63 x 78 x 14 = 1788696.

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20 x 20 grid?

As in Problem #8, the real challenge here is finding a way to store that massive grid so that we can analyze it through traditional methods. Here was my solution:

Solution #1: Read From File and Brute Force Approach

Like in Problem #8, I thought the best way to approach this question would be by copy pasting the massive block of text into a file (I called the file “PE11Grid”) and then using a Python script to read from the file and analyze the data. Once I read from the file, I essentially used a brute force approach, testing every product of four adjacent numbers and storing a running maximum product. Clearly this method can be optimized by using a “running product” system where new numbers are multiplied with the running product and old values are divided out, but I didn’t want to deal with casework involving the presence of “00” cells.

Here is an implementation of this brute force method in Python 2.7:

'''
Author: Walker Kroubalkian
Brute Force Approach to Project Euler Problem #11
'''

import time
f = open("PE11Grid.txt","r")

if f.mode=="r":
     contents = f.readlines()
     realContents=[]
     for x in contents:
          realContents.append(map(int,x.split()))
else:
     raise ValueError("Cannot read from file")

def projectEulerProblemEleven(grid,l):
     rows = len(grid)
     cols = len(grid[0])
     maxProduct = -1
     for r in range(rows):
          for c in range(cols-l):
               total = 1
               for x in range(l):
                    total*=grid[r][c+x]
               if(total>maxProduct):
                    maxProduct = total
     for r in range(rows-l):
          for c in range(cols):
               total = 1
               for x in range(l):
                    total*=grid[r+x][c]
               if(total>maxProduct):
                    maxProduct = total
     for r in range(rows-l):
          for c in range(cols-l):
               total = 1
               for x in range(l):
                    total*=grid[r+x][c+x]
               if(total>maxProduct):
                    maxProduct = total
     for r in range(rows-l):
          for c in range(l-1,cols):
               total = 1
               for x in range(l):
                    total*=grid[r+x][c-x]
               if(total>maxProduct):
                    maxProduct = total
     return maxProduct

start = time.time()
print projectEulerProblemEleven(realContents,4)
print("--- %s seconds ---" % (time.time()-start))

'''
Prints
70600674
--- 0.000658988952637 seconds ---
for input of given grid
'''

Once again, these types of problems are only helpful in the sense that they teach you how to read from large amounts of data. The first few tend to have fairly standard solutions.

That is all. Thanks for reading!

Project Euler Problem #10:

Problem #10 is an example of how some common functions that are used in certain problems can also be used for other problems down the line. In my post for Problem #7, I discussed the Sieve of Eratosthenes, and I presented an implementation of it in Python 2.7. Perhaps unsurprisingly, this function can be used to solve many other problems such as Problem #10. The problem reads:

Project Euler Problem 10: Summation of primes 
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

It should be obvious to anyone familiar with the Sieve of Eratosthenes that it is exactly what we need to solve this problem. Here is the solution I found:

Solution #1: Sieve Approach

We just use the sieve to find all of the primes less than 2,000,000 and then add all of them up. Here is an implementation of this method in Python 2.7 using a copy-pasted version of the Sieve function I implemented in Problem #7:

'''
Author: Walker Kroubalkian
Sieve Approach to Project Euler Problem #10
'''

import time

def sieveEratosthenes(n):
    myPrimes = []
    
    primePossible = [True]*(n+1)
    primePossible[0] = False
    primePossible[1] = False

    for (i,possible) in enumerate(primePossible):
        if(possible):
            for x in range(i*i, (n+1), i):
                primePossible[x] = False
            myPrimes.append(i)

    return myPrimes

def projectEulerProblemTen(n):
    allPrimes = sieveEratosthenes(n)
    total = 0
    for p in allPrimes:
        total+=p
    return total

start = time.time()
print projectEulerProblemTen(2000000)
print ("--- %s seconds ---" % (time.time() - start))

'''
Prints

142913828922
--- 0.402328968048 seconds ---
for input of n=2000000
'''

As shown above, the Sieve of Eratosthenes is even efficient at listing all primes up to crazy large numbers such as 2,000,000. And with that, we have officially entered the double-digits of problems solved. I got the achievement “Decathlon” for solving this problem as it meant that I had solved 10 problems in a row.

Thanks for reading!

Project Euler Problem #9:

Problem #9 features what is possibly the most famous theorem in all of mathematics: The Pythagorean Theorem. However, unlike typical discussion of the Pythagorean Theorem which involves right triangles in Euclidean geometry, this problem is more concerned with investigating the theorem as a Diophantine Equation. The problem reads:

Project Euler Problem 9: Special Pythagorean triplet 
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which

a^2 + b^2 = c^2 

For example, 3^2+4^2 = 9 + 16 = 25 = 5^2. 

There exists exactly one Pythagorean triplet for which a+b+c = 1000. 
Find the product abc.

Luckily, there are some useful facts about Pythagorean triplets which we can use to our advantage while interpreting the theorem as a Diophantine equation. I chose to generalize this problem by finding the maximum product of all Pythagorean triplets with a given sum or returning -1 if no such triplets exist. Here is the solution I found:

Solution #1: General Pythagorean Triplet

As it turns out, prior investigation of Pythagorean triples has resulted in a useful method of generating Pythagorean triples. One can easily verify that for all positive integers m and n such that m>n, the triple (m^2-n^2, 2mn, m^2+n^2) is a Pythagorean triple. According to Wikipedia, this generator is one of the many facts that is called Euclid’s Formula.

It is a bit more difficult to show that this generator can generate all primitive Pythagorean triples. A primitive Pythagorean triple is a triple (a,b,c) which satisfies the condition and the extra condition that gcd(a,b,c) = 1. I will not write the proof of this fact here. Unfortunately, this generator is not perfect, as some non-primitive triples such as (9, 12, 15) cannot be generated by Euclid’s Formula. Instead, we must use the generalized generator for Pythagorean triplets: (d(m^2-n^2), d(2mn), d(m^2+n^2)) for positive integers d, m, and n such that m>n.

Using this generator, the sum of the sides of a general Pythagorean triple is d(2m^2 + 2mn) = 2dm(m+n). Thus, we have reduced this diophantine equation to finding integer solutions to 2dm(m+n) = 1000 such that m>n.

I attempted to solve this Diophantine equation by iterating through the possible values of d and then iterating through the possible values of m. It is worth noting that m < m+n < 2m by the definition of the Pythagorean triplet. Thus, m^2 < 1000/(2d) < 2m^2. Using this fact, we can bound the possible values of m.

Here is an implementation of this method in Python 2.7:

'''
Author: Walker Kroubalkian
General Pythagorean Triple Approach to Project Euler Problem #8
'''

import time
from math import sqrt

def listFactorsGivenFactorization(p,e):
    total = []
    if(len(p) >= 1):
        for x in range(e[0]+1):
            total.append(p[0]**x)
    else:
        return [1]
    previousTotal = listFactorsGivenFactorization(p[1:],e[1:])
    actualTotal = []
    for a in total:
        for b in previousTotal:
            actualTotal.append(a*b)
    return actualTotal

def listFactors(n):
    primes = []
    exponents = []
    c = 2
    while(c<=sqrt(n)):
        if(n%c==0):
            primes.append(c)
            t = 0
            while(n%c==0):
                n/=c
                t+=1
            exponents.append(t)
        c+=1
    if(n>1):
        primes.append(n)
        exponents.append(1)
    return sorted(listFactorsGivenFactorization(primes,exponents))

def projectEulerProblemNine(n):
    if(n%2==1):
        return -1
    maxProduct = -1
    possibleD = listFactors(n/2)
    n/=2
    for d in possibleD:
        newProduct = n/d
        lowerBound = int(sqrt(newProduct/2))
        upperBound = int(sqrt(newProduct))
        for m in range(lowerBound,upperBound+1):
            if(m>0 and newProduct%m==0):
                o = newProduct/m - m
                if(0<o<m):
                    possible = d*d*d*(m*m-o*o)*(2*m*o)*(m*m+o*o)
                    if(possible>maxProduct):
                        maxProduct = possible
    return maxProduct

start = time.time()
print projectEulerProblemNine(1000)
print ("--- %s seconds ---" % (time.time()-start))

'''
Prints

31875000
--- 4.91142272949e-05 seconds ---

for input of n=1000
'''

As shown above, even with a very sloppy implementation of this method, using math can make solving complex problems far more efficient.

Thanks for reading! See you tomorrow.

Project Euler Problem #8:

Problem #8 is the first of many to involve finding some answer among a large amount of data. In this case, we are asked to investigate a crazy 1000-digit number. Here is the statement of the problem:

Project Euler Problem 8: Largest product in a series
The four adjacent digits in the 1000-digit number that have the greatest product are 9*9*8*9 = 5832.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

In most programming languages, just loading this crazy number into a variable would result in an error. As a result, I thought it would be better to store this number in a file and then to have my script read the number from the file and store it as a string. This led me to the following solution:

Solution #1: Brute Force, File-Reading Approach

Solving this problem is not the interesting part of this problem. The interesting part of this problem is loading the 1000-digit number into a variable which I can analyze in my script. As mentioned above, the way I did this was by copy pasting the 20 50-digit lines into a file which I titled “PE8Grid.txt”. Then I read from this file in my Python 2.7 script. (Shoutouts to Guru99 for teaching me how to read files in Python)

Regardless of how the number is loaded, solving the problem is quite straightforward. I opted for iterating through the digits and from each possible starting point for the 13-adjacent digits, I would independently calculate the product of those digits. If the product was greater than a running maximum, I would reset the running maximum. Clearly this method can be optimized by simply multiplying each new digit while dividing out old digits, but I didn’t want to deal with any messy casework involving ‘0’ digits. Here is an implementation of this method in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Brute Force Approach to Project Euler Problem #8
 '''
 import time
 f = open("PE8Grid.txt","r")
 if f.mode == "r":
     contents = f.readlines()
     realContents = []
     for x in contents:
         if(x[len(x)-1] == "\n"):
             realContents.append(x[0:len(x)-1])
         else:
             realContents.append(x)
 else:
     raise ValueError("Cannot read from file")
 def projectEulerProblemEight(lines, n):
     s = ""
     maxProduct = 0
     for x in lines:
         s+=x
     length = len(s)
     for i in range(length-n):
         total = 1
         for j in range(n):
             total*=int(s[i+j])
         if(total>maxProduct):
             maxProduct = total
     return maxProduct
 start = time.time()
 print projectEulerProblemEight(realContents, 13)
 print ("--- %s seconds ---" % (time.time()-start))
 '''
 Prints
 23514624000
 --- 0.00584602355957 seconds ---
 for input of n = that crazy number
 '''

While this problem may be boring compared to the typical Project Euler problem, knowing how to read from files will prove to be an invaluable skill as we attempt more problems. That’s it folks! Thanks so much for reading.

Design a site like this with WordPress.com
Get started