The bouncing sequence Let us define a sequence.  We will say that \$a(n)\$ is the smallest number, \$x\$, that has the following properties:


\$x\$ and \$n\$ are co-prime (they share no factor)
\$x\$ does not appear earlier in the sequence
\$|n - x| &gt; 1\$


Unlike most sequences the domain and range of our sequence are the integers greater than 1.



Let us calculate the first couple of terms.

\$a(2)\$, must be at least 4, but 4 and 2 share a factor of 2 so \$a(2)\$ must be 5.

\$a(3)\$, must be at least 5 but 5 is taken by \$a(2)\$, so it is at least 6, but 6 shares a factor with 3 so it must be at least 7, 7 fulfills all three requirements thus \$a(3)=7\$.

\$a(4)\$ 


2 Shares a factor
3 Too close
4 Too close
5 Too close
6 Shares a factor
7 Taken by a(3)
8 Shares a factor
9 is good


\$a(5)\$


2 is good




Task

In this challenge you are to write a program that takes a number greater than 1 and returns \$a(n)\$.

This is a code-golf question so answers will be scored in bytes, with fewer bytes being better.

Test Cases

Here are the first couple terms of the sequence (They are of course 2 indexed):

5,7,9,2,11,3,13,4,17,6,19,8,23,22,21,10,25,12,27,16,15,14


Bonus Fun fact

As proven by Robert Israel on Math.se (link) this sequence is its own inverse, that means that \$a(a(n)) = n\$ for all n.

OEIS

After asking this question I submitted this sequence to the OEIS and after a few days it was added.

OEIS A290151
Haskell, 61 bytes



f n=[i|i&lt;-[2..],gcd i n&lt;2,all((/=i).f)[2..n-1],abs(n-i)&gt;1]!!0


Try it online!

I'm fairly new to Haskell, so any golfing tips are appeciated.

Thanks to Wheat Wizard for 2 bytes and nimi for 4 bytes

Explanation:

f n=[i|i&lt;-[2..],gcd i n&lt;2,all((/=i).f)[2..n-1],abs(n-i)&gt;1]!!0
f n=                                                          -- define a function f :: Int -&gt; Int
    [i|i&lt;-[2..],                                              -- out of positive integers greater than two
                gcd i n&lt;2,                                    -- gcd of i and n is 1
                          all((/=i).f)[2..n-1],               -- i isn't already in the sequence
                                               abs(n-i)&gt;1]    -- and |n-i| &gt; 1
                                                          !!0 -- take the first element