Project Euler 128 - Hexagonal Tile Differences

Official link: https://projecteuler.net/problem=128

Thought Process

Very fun problem! I worked through this problem by first trying to find the neighbours of a given number and then I was able to prove that the maximum of PD(n) is 3 and I was able to prove exactly when this will happen.

Firstly, I categorize each number by which level its on, i, then each level can be broken down into 6 compartments of size i (the sides of the hexagon), k, and then it's position in that compartment, 0 <= r < i.

Here's an example of the breakdown:

Then every number can be represented by a tuple (i, k, r). For example 21 = (3, 0, 1), 37 = (3, 5, 2).

From here it is just simple to find the neighbours of any number by splitting into case work. Suppose our given number n = (i, k, r), define v = 1 + 6*(iC2) where iC2 means i choose 2, then it is clear that n = v + ik + r + 1

I give the final answer only as the working is simple tedious calculations. note that these are only true for level 2 onwards, but it doesn't matter since we easily check that PD(1) = PD(2) = 3 so the first 2 levels are done.

This is a full proof that the maximum value of PD(n) is 3, furthermore it shows that we only need to consider the first and last elements of a row! 

Now the rest is simple, for each row just test if the required values are prime, if they all are then we have found an n such that PD(n) = 3.

Interactive Code

Input an Integer (yourinput)

Code will output the yourinput-th number x such that PD(x) = 3