Problem #61 Difficulty: 20%

Cyclical Figurate Numbers

Solution Language: Java

The problem

Find the only ordered cycle of six 4-digit numbers in which the last two digits of each number are the first two of the next (wrapping around), and the six are one each of triangular, square, pentagonal, hexagonal, heptagonal and octagonal. Report their sum.

My solution

First a HashSet of 4-digit numbers is built for each of the six polygonal formulas. One loop over n fills all six; it runs until the triangular numbers, the slowest-growing of the six, pass 9,999, so every set is complete.

Then the code tries orderings of the six types around the cycle, generating them with the next-permutation routine from my Problem 24 solution. For each ordering, check runs six nested loops, one per type, and only goes deeper when the next number’s first two digits (x / 100) match the previous number’s last two (x % 100). The innermost loop also checks that the sixth number links back to the first. The first full cycle found has its sum printed.

for(int c : polygons[indices[2]-48]) {
  if(c / 100 != b % 100)
    continue;

  for(int d : polygons[indices[3]-48]) {
    if(d / 100 != c % 100)
      continue;

The prefix check prunes heavily, since each set has only around one number per two-digit prefix on average.