login
Number of permutations of 1..2n in which the sum of every two adjacent elements is a prime number, including the sum of first and last elements.
0

%I #6 May 10 2013 12:45:48

%S 2,8,12,32,960,12288,40320,1296384,13862592

%N Number of permutations of 1..2n in which the sum of every two adjacent elements is a prime number, including the sum of first and last elements.

%C For 2n=4 we have a(2) = 8. One of the permutations is 1 4 3 2. Let's check: 1 + 4 = 5 is a prime number; 4 + 3 = 7 is a prime number; 3 + 2 = 5 is a prime number; 2 + 1 = 3 is a prime number; so we say it's a legal permutation.

%C a(n) = 4*n*A051252(n), n>1. - _Vladeta Jovovic_, Feb 02 2007

%C As explicitly checked for 2<=n<=9, a(n)=4*n*A051252(n). This is twice the length of the permutation multiplied by A051252(n), where the factor 4n counts the permutations generated by any of the 2n cyclic shifts or any of the 2n cyclic shifts followed by reversal. The exception is for n=1, where reversal and shift yield the same image of the permutation. - _R. J. Mathar_, Nov 02 2007

%e a(2) = 8 because we can generate 8 different permutations:

%e 1 2 3 4

%e 1 4 3 2

%e 2 1 4 3

%e 2 3 4 1

%e 3 2 1 4

%e 3 4 1 2

%e 4 1 2 3

%e 4 3 2 1

%e in which the sum of every two adjacent elements is a prime number, including the sum of first and last elements.

%o /* I write the program in C++, but it's not very efficient. I hope someone can improve the algorithm. */ #include <vector> #include <iostream> #include <algorithm> using namespace std; const bool isPRIME[41] = {0, 0,1,1,0,1,0,1,0,0,0, 1,0,1,0,0,0,1,0,1,0, 0,0,1,0,0,0,0,0,1,0, 1,0,0,0,0,0,1,0,0,0 }; int smartP_3(int n,bool p){ vector<int> arr(n - 1); for(int i = n - 2;i >= 0;--i) arr[i] = i + 2; int cnt = 0,last_i = (n > 2 ? n - 3 : 0); ostream_iterator<int> out(cout," "); do{ if(!isPRIME[1 + arr[0]] || !isPRIME[1 + arr[n - 2]]) continue; int i = last_i; for(;i < n - 2 && isPRIME[arr[i] + arr[i + 1]];++i); if(i == n - 2){ for(i = 0;i < last_i && isPRIME[arr[i] + arr[i + 1]];++i); if(i == last_i){ cnt += n; if(p){ cout<<"1 "; copy(arr.begin(),arr.end(),out); cout<<endl; } }else last_i = i; }else last_i = i; }while(next_permutation(arr.begin(),arr.end())); return cnt; } int main() { int n; while(cin>>n){ if(n <= 20 && n > 1){ long start = clock(); cout<<smartP_3(n,false)<<endl; cout<<"Time: "<<(clock() - start)<<" ms"<<endl; } } }

%K nonn,more

%O 1,1

%A DoZerg (daidodo(AT)gmail.com), Feb 01 2007

%E Can be extended using A051252.

%E a(8) and a(9) from _R. J. Mathar_, Nov 02 2007