Magic 5-gon Ring — Project Euler (Problem 68)

Yet another exciting math problem that requires an algorithmic approach to arrive at a quick solution! There is a pen-paper approach to it too, but this post assumes we’re more interested in discussing the programming angle.

First, the problem:

Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), each solution can be described uniquely. For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.

It is possible to complete the ring with four different totals: 9, 10, 11, and 12. There are eight solutions in total.

Total Solution Set:
9 4,2,3; 5,3,1; 6,1,2
9 4,3,2; 6,2,1; 5,1,3
10 2,3,5; 4,5,1; 6,1,3
10 2,5,3; 6,3,1; 4,1,5
11 1,4,6; 3,6,2; 5,2,4
11 1,6,4; 5,4,2; 3,2,6
12 1,5,6; 2,6,4; 3,4,5
12 1,6,5; 3,5,4; 2,4,6
By concatenating each group it is possible to form 9-digit strings; the maximum string for a 3-gon ring is 432621513.

Problem

Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16- and 17-digit strings. What is the maximum 16-digit string for a “magic5-gon ring?

Algorithm

In attempting this problem, I choose to label the 5 inner nodes as i, j, k, l, and m.
α, β, γ, δ, and θ being the corresponding outer nodes.

Let x be the sum total of each triplet line, i.e.,

x = α + i + j = β + j + k = γ + k + l = δ + l + m = θ + m + i

magic5gon

First Observation:
For the string to be 16-digits, 10 has to be in the outer ring, as each number in the inner ring is included in the string twice. Next, we fill the inner ring in an iterative manner.

Second Observation:
There 9 numbers to choose from for the inner ring — 1, 2, 3, 4, 5, 6, 7, 8 and 9.
5 have to be chosen. This can be done in 9C5 = 126 ways.
According to circular permutation, if there are n distinct numbers to be arranged in a circle, this can be done in (n-1)! ways, where (n-1)! = (n-1).(n-2).(n-3)…3.2.1. So 5 distinct numbers can be arranged in 4! permutations, i.e., in 24 ways around a circle, or pentagonal ring, to be more precise.
So in all, this problem can be solved in 126×24 = 3024 iterations.

Third Observation:
For every possible permutation of an inner-ring arrangement, there can be one or more values of x (triplet line-sum) that serve as a possible contenders for a “magic” string whose triplets add up to the same number, x. To ensure this, we only need that the values of α through θ of the outer ring are distinct, different from the inner ring, with the greatest of these equal to 10.
Depending on the relative positioning of the numbers in the inner ring, one can narrow the range of x-values one might have to check for each permutation. To zero-down on such a range, let’s look at an example. Shown in the figure below is a randomly chosen permutation of number in the inner ring – 7, 2, 3, 4 and 5, in that order.

magic5gonInstance

So 10, 9, 8, 6 and 1 must fill the outer circle. It’s easy to notice that the 5, 7 pair is the greatest adjacent pair. So whatever x is, it has to be at least 5 + 7 + 1 = 13 (1 being the smallest number of the outer ring). Likewise,  2, 3 is the smallest adjacent pair, so whatever x is, it can’t be any more than 2 + 3+ 10 = 15 (10 being the largest number of the outer ring). This leaves us with a narrow range of x-values to check – 13, 14 and 15.

Next, we arrange the 5 triplets in clock-wise direction starting with the triplet with the smallest number in the outer ring to form a candidate string. This exercise when done for each of the 3024 permutations will shortlist a range of candidates, of which, the maximum is chosen.

That’s all there is to the problem!

Here’s the Python Code. It executes in about a tenth of a second!

from itertools import permutations
from itertools import combinations
# array of candidate solutions empty at the beginning
record = []
# choose 5 numbers for inner cells between 1 and 9; there are 9C5 combinations
# the problem ask for a 16-digit number, so 10 is not to be included in inner cells
cells = range(1,10)
inner_cells = [map(int,comb) for comb in combinations(cells,5)]
# code to calculate min and max couple in an array
def minCouple(array):
answer = array[0]+array[-1]
for i in xrange(len(array)-1):
coupleSum = array[i] + array[i+1]
if coupleSum < answer:
answer = coupleSum
return answer
def maxCouple(array):
answer = 0
for i in xrange(len(array)-1):
if i==0:
coupleSum = array[0]+ array[-1]
if coupleSum > answer:
answer = coupleSum
else:
coupleSum = array[i]+ array[i+1]
if coupleSum > answer:
answer = coupleSum
return answer
# Algorithm
for array in inner_cells:
pivot = array[0]
perm_array = array[1:]
perms = [map(int,perm) for perm in permutations(perm_array,4)]
for perm in perms:
checkArray = perm
checkArray.insert(0,pivot)
outerRing = [el for el in range(1,11) if el not in checkArray]
xMax = minCouple(checkArray) + max(outerRing)
xMin = maxCouple(checkArray) + min(outerRing)
if xMax >= xMin:
for x in xrange(xMin, xMax+1):
i = checkArray[0]
j = checkArray[1]
k = checkArray[2]
l = checkArray[3]
m = checkArray[4]
alpha = x-i-j
beta = x-j-k
gamma = x-k-l
delta = x-l-m
theta = x-m-i
outerCalculated = [alpha, beta, gamma, delta, theta]
if sorted(outerCalculated) == sorted(outerRing):
a = [alpha, i, j]
b = [beta, j, k]
c = [gamma, k, l]
d = [delta, l, m]
e = [theta, m, i]
min_val = min(alpha, beta, gamma, delta, theta)
if alpha == min_val:
append = a+b+c+d+e
elif beta == min_val:
append = b+c+d+e+a
elif gamma == min_val:
append = c+d+e+a+b
elif delta == min_val:
append = d+e+a+b+c
elif theta == min_val:
append = e+a+b+c+d
l = [str(i) for i in append]
s = ''.join(l)
integer_list = int(s)
record.append(integer_list)
print max(record)
view raw euler68.py hosted with ❤ by GitHub

Ans: 6531031914842725

Consecutive Prime Sum — Project Euler (Problem 50)

Many problems in Project Euler relate to working with primes. I use primesieve-python to help solve such problems. It consists of Python bindings for the primesieve C++ library. Generates primes orders of magnitude faster than any pure Python code. Features:

  • Generate a list of primes
  • Count primes and prime k-tuplets
  • Print primes and prime k-tuplets
  • Find the nth prime
  • Iterate over primes using little memory

Anyway, here’s Problem 50 from Project Euler:

ProjectEuler50

Here’s how I did it:

# Question: Which prime, below one-million, can be written as the sum of the most consecutive primes
from primesieve import *
from math import *
# Generate list of primes under a million
primes_under_million = generate_primes(10**6)
# Sum of consecutive primes is of order 0.5(n^2)(logn)
# Calculate 'n' so that sum of consecutive primes is less than a million (and not necessarily prime)
nsum = 1
n = 1
while nsum < 10**6:
nsum = 0.5*(n**2)*(log(n, e))
n += 1
# Calculate index so that sum of first 'index' consecutive primes is under a million and also prime
primes_subset = primes_under_million[:n]
nsum = sum(primes_under_million[:n])
while nsum > 10**6:
n -= 1
nsum = sum(primes_under_million[:n])
primes_sum = 0
index = 0
for i in range(len(primes_subset)):
if i % 2 == 1:
pass
else:
sumprimes = sum(primes_subset[:i])
if sumprimes > primes_sum and sumprimes < 10**6 and sumprimes in primes_under_million:
primes_sum = sumprimes
index = i
# Print out sum of consecutive primes till 'index', index, n
# print primes_sum, index, n
# Check consecutive primes within a range (index to n) such that their number is greater than index and maximum
j = index + 1
start = 0
while j <= n:
while (j-start) >= (n-index):
sumprimes = sum(primes_subset[start:j])
if sumprimes > primes_sum and sumprimes in primes_under_million:
primes_sum = sumprimes
start += 1
j += 1
start = 0
print primes_sum
view raw euler50.py hosted with ❤ by GitHub

Answer: 997651

Largest Product in a Grid — Project Euler (Problem 11)

I started solving Project Euler problems this month. Check out the Project Euler tab of this blog for a list of the problems I’ve solved (with solutions) till date. Here’s a problem you might find interesting:

ProjectEuler11

Here’s my solution using Python (I basically search through the entire matrix which is of O() complexity):

I first copy the maxtrix into a text file euler11.txt so that it can be later read into Python

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
view raw euler11.txt hosted with ❤ by GitHub

I then execute the following code from the same working directory as euler11.txt
# import numpy module for matrix operations
from numpy import *
# read the file with the matrix of numbers
filename = 'euler11.txt'
# store each line of the file into an array
with open(filename, "r") as ins:
array = []
for line in ins:
array.append(line)
print array
# create a new array that converts the number strings into number integers
newArray = []
for i in array:
j = i.split(' ')
k = [int(n) for n in j]
newArray.append(k)
print newArray
# convert the array of integers into a matrix of integers
problemMatrix = matrix(newArray)
print problemMatrix
# set initial maximum product to be a dummy number, say 1
maxProd = 1
# search all combinations for maximum product
for i in range(16):
for j in range(16):
prod1 = problemMatrix[i,j]*problemMatrix[i+1,j]*problemMatrix[i+2,j]*problemMatrix[i+3,j]
if prod1 > maxProd:
maxProd = prod1
prod2 = problemMatrix[i,j]*problemMatrix[i,j+1]*problemMatrix[i,j+2]*problemMatrix[i,j+3]
if prod2 > maxProd:
maxProd = prod2
prod3 = problemMatrix[i,j]*problemMatrix[i+1,j+1]*problemMatrix[i+2,j+2]*problemMatrix[i+3,j+3]
if prod3 > maxProd:
maxProd = prod3
prod4 = problemMatrix[19-i,j]*problemMatrix[18-i,j+1]*problemMatrix[17-i,j+2]*problemMatrix[16-i,j+3]
if prod4 > maxProd:
maxProd = prod4
print maxProd
view raw euler11.py hosted with ❤ by GitHub

Answer: 70600674