We are given a number $N$ such that $3 \leq N \leq 50000,$ and we have to find a sequence consisting of $N$ numbers, where:
All numbers are distinct;
All numbers lie between $1$ to $10^{19}$;
Two adjacent numbers are NOT co-prime;
Three adjacent numbers are co-prime.
Note that in this array if the sequence is $S_0,S_1,S_2,...,S_n$, we consider $S_1$ to be adjacent to $S_n$. So, $S_{n-1},S_0,S_1$ should have $\gcd=1$. Similarly, $S_{n-1}$ and $S_0$ should have a $\gcd$ of more than 1. Same goes for $S_{n-2}$ as well.
Example: If $N=3$, then our sequence can be 6 15 10 since $\gcd(6,15,10)=1, \gcd(6,15)$ and $\gcd(10,15)$ is not 1.
My approach: I generated prime numbers up to $N$ using an algorithm. I multiply all the elements to the element on its right and finally multiply the rightmost ($S_{n-1}$) element by 2.
For example, if $N=4$:
- Step 1 (Generating primes): 2 3 5 7
- Step 2 (multiplying): 6 15 35 14
which is my required sequence. But in the question, $N$ can be as large as $50000$ and the elements should be in the range $[1,10^9]$. By using my approach, I am missing out some primes in between like 10, 14, etc.
How can I make a better algorithm? Also I have to write "Impossible" in case making the sequence isn't possible. I can't find what will be the condition when we can't make the sequence.
Can anyone suggest anything better?
Consider $1001$ primes lower than $10000$ (it is possible, look on the internet). Consider the complete graph such that all they are its vertices. Every vertex has an even degree, therefore the graph has a cyclic path $P$ that goed exactly once through every edge.
In your array, take as $i$-th number the product of the two primes that are the vertices of the $i$-th edge in $P$. The array has size $500*1001$, keep the first $N$ elements.
Since $P$ goes exactly once through each edge, the elements of the array are pairwise distinct.
Since every element is the product of two primes lower than $10000$, no element is higher than $10^8$.
Since $P$ is a path, no two consecutive elements are coprime.
For three consecutive elements not to be coprime, you would need three consecutives edges in $P$ that have a common vertex, this is absurd.
Edit: with five primes 2,3,5,7,11;
A fitting path is (2,3), (3,5), (5,2), (2,7), (7,11), (11,3), (3,7), (7,5), (5,11), (11,2) (draw the graph). The sequence is 6 15 10 14 77 33 21 35 55 22.