Select Page

Project Euler 8 Problem Statement

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934699893520312774506326239578318016984…

Find the greatest product of 13 adjacent digits in the 1000-digit number.

Solution

We begin by opening and reading the file “pe8.txt” and concatenate each line into one long string by stripping whitespace (which includes the new line character, \n) from the end of the lines.

Next, each character is separated, converted to an integer digit, and stored to a list named d.

d = map(int, ''.join(line.rstrip() for line in open('pe8.txt')))

The variable L defines the search length, 13 for this exercise, and we make sure there are enough digits to search. If not we exit printing “None.”

If there are enough digits, we consider all 13-digit sets and store their product. The for loop’s index, i,  is the starting index of the next set inside the string and the reduce function multiplies each 13-digit set together.

Lastly, we capture the maximum product of all sets.

L = 13
print 'Greatest product of', L, 'consecutive \ndigits =', 
print "None."  if L>len(d) else  \
            max(reduce(mul, d[i:i+L]) for i in xrange(len(d)-L+1))

Easy mistakes to make

80% of the Python solutions listed in the Project Euler forum are wrong as they don’t consider the last digit in the search space. Because the solution to this problem lies in the middle somewhere, these programs calculate a correct response in this instance. If you were to run them with the following parameters they would fail by erroneously producing a zero instead of 18:
d = [0,0,0,1,9,2]
L = 3

Further, many of these same erroneous programs would return an error or zero (a distinct possibility) which could be misleading; it’s better to return some indication that an answer cannot be calculated, such as “None,” to indicate an undefined condition:
d = [0,0,0,1,9,2]
L = 13

HackerRank version

HackerRank Project Euler 8 steps up the complexity a bit by running up to 100 trials and changing the search length from a fixed 13 digits to a variable 1 through 7 digits. The search object can range from 1 to 1000 digits and will be at least the size of the search length.

Python 2.7 Source

Last Word

  • The file is available in the REPL window by clicking the  icon.
  • The backslash (‘\’) at the end of in line 6 of the Python program is used to continue the program statement to the next line. It makes programs more readable.