arrange sequence of numbers such that sum of adjacent number is a prime number

2.5k Views Asked by At

What would be the best way to arrange a sequence of numbers such that the sum of any two adjacent number is a prime number E.g.: 7,6,5,2,1,4,3 is one such sequence for numbers between 1 to 7.

1

There are 1 best solutions below

0
On

As far as I see it, the easiest way to tackle this problem is to break it into two parts that are more well defined:

  1. Generate an undirected graph, so that each vertex is a number in this list of numbers and each edge links a pair of numbers that can be adjacent. Or in other words, generates a graph that connects any two numbers that has a prime number sum. This can be done in quite a straightforward manner by looping through 2 indices.

  2. Find a Hamiltonian path for the aforementioned graph. That is the sequence you want. This is somewhat a well-studied problem and a number of algorithms exist. You just need to pick one and there might be a native implementation in software like Mathematica. This would be even faster than O(n^2).

Of course you can find multiple ways to speed up the first step, if you know a bit more about what kind of list of numbers you are dealing with.