Count of permutations of first N positive integers such that sum of any two consecutive numbers is prime - GeeksforGeeks

20 Dec, 2021
Find the number of permutations of first N positive integers such that the sum of any two consecutive numbers is prime where all the cyclic permutations are considered the same.
Note: The sum of the first and last element must be prime as well.
Example:
Input: N = 6Output: 2Explanation: The two valid permutations are {1, 4, 3, 2, 5, 6} and {1, 6, 5, 2, 3, 4}. The permutation like {3, 2, 5, 6, 1, 4} is considered a cyclic permutation of the 1st one and hence not included.
Input: N = 3Output: 0Explanation: No valid permutations exist.
Approach: The given problem can be solved by using recursion and backtracking. It can be observed that to find the distinct number of cycles, without loss of generality, the cycle should start with 1. An isPrime[] array can be created using the Sieve of Eratosthenes which stores whether a number is prime or not. Therefore, create a recursive function and add elements in the permutation such that its sum with the last element is prime. Increment the permutation count if the sum of the first and last element is also prime. 
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long // Initialize a global variable Nconst int maxn = 100; // Stores the final count of permutationsll ans = 0; // Stores whether the integer is primebool isPrime[maxn];bool marked[maxn]; void SieveOfEratosthenes(int n){    memset(isPrime, true, sizeof(isPrime));     for (int p = 2; p * p <= n; p++) {         // If prime[p] is not changed,        // then it is a prime        if (isPrime[p] == true) {             // Update all multiples of P            for (int i = p * p; i <= n; i += p)                isPrime[i] = false;        }    }} // Function to find the number of valid permutationsvoid countCycles(int m, int n, int prev, int par){    // If a complete permutation is formed    if (!m) {        if (isPrime[prev + 1]) {             // If the sum of 1st and last element            // of the current permutation is prime            ans++;        }        return;    }     // Iterate from par to N    for (int i = 1 + par; i <= n; i++) {         if (!marked[i] && isPrime[i + prev]) {             // Visit the current number            marked[i] = true;             // Recursive Call            countCycles(m - 1, n, i, 1 - par);             // Backtrack            marked[i] = false;        }    }} int countPermutations(int N){    // Finding all prime numbers upto 2 * N    SieveOfEratosthenes(2 * N);     // Initializing all values in marked as 0    memset(marked, false, sizeof(marked));     // Initial condition    marked[1] = true;     countCycles(N - 1, N, 1, 1);     // Return Answer    return ans;} // Driver codeint main(){    int N = 6;    cout << countPermutations(N);     return 0;}
// Java implementation for the above approachimport java.util.*; class GFG{ // Initialize a global variable Nstatic int maxn = 100; // Stores the final count of permutationsstatic int ans = 0; // Stores whether the integer is primestatic boolean []isPrime = new boolean[maxn];static boolean []marked = new boolean[maxn]; static void SieveOfEratosthenes(int n){    for (int i = 0; i <isPrime.length; i += 1) {        isPrime[i]=true;    }      for (int p = 2; p * p <= n; p++) {         // If prime[p] is not changed,        // then it is a prime        if (isPrime[p] == true) {             // Update all multiples of P            for (int i = p * p; i <= n; i += p)                isPrime[i] = false;        }    }} // Function to find the number of valid permutationsstatic void countCycles(int m, int n, int prev, int par){    // If a complete permutation is formed    if (m==0) {        if (isPrime[prev + 1]) {             // If the sum of 1st and last element            // of the current permutation is prime            ans++;        }        return;    }     // Iterate from par to N    for (int i = 1 + par; i <= n; i++) {         if (!marked[i] && isPrime[i + prev]) {             // Visit the current number            marked[i] = true;             // Recursive Call            countCycles(m - 1, n, i, 1 - par);             // Backtrack            marked[i] = false;        }    }} static int countPermutations(int N){       // Finding all prime numbers upto 2 * N    SieveOfEratosthenes(2 * N);     // Initializing all values in marked as 0    for (int i = 0; i <marked.length; i += 1) {        marked[i]=false;    }     // Initial condition    marked[1] = true;     countCycles(N - 1, N, 1, 1);     // Return Answer    return ans;} // Driver codepublic static void main(String[] args){    int N = 6;    System.out.print(countPermutations(N)); }} // This code is contributed by 29AjayKumar
# python implementation for the above approach import math # Initialize a global variable Nmaxn = 100 # Stores the final count of permutationsans = 0 # Stores whether the integer is primeisPrime = [True for _ in range(maxn)]marked = [False for _ in range(maxn)]  def SieveOfEratosthenes(n):    global ans    global isPrime    global marked     for p in range(2, int(math.sqrt(n))+1):                 # If prime[p] is not changed,                # then it is a prime        if (isPrime[p] == True):                         # Update all multiples of P            for i in range(p*p, n+1, p):                isPrime[i] = False  # Function to find the number of valid permutationsdef countCycles(m, n, prev, par):    global ans    global isPrime    global marked     # If a complete permutation is formed    if (not m):        if (isPrime[prev + 1]):                         # If the sum of 1st and last element                        # of the current permutation is prime            ans += 1         return         # Iterate from par to N    for i in range(1+par, n+1):        if (not marked[i] and isPrime[i + prev]):                         # Visit the current number            marked[i] = True             # Recursive Call            countCycles(m - 1, n, i, 1 - par)             # Backtrack            marked[i] = False  def countPermutations(N):    global ans    global isPrime    global marked     # Finding all prime numbers upto 2 * N    SieveOfEratosthenes(2 * N)     # Initial condition    marked[1] = True     countCycles(N - 1, N, 1, 1)     # Return Answer    return ans  # Driver codeif __name__ == "__main__":     N = 6    print(countPermutations(N))     # This code is contributed by rakeshsahni
// C# implementation for the above approachusing System; public class GFG{   // Initialize a global variable N  static int maxn = 100;   // Stores the final count of permutations  static int ans = 0;   // Stores whether the integer is prime  static bool []isPrime = new bool[maxn];  static bool []marked = new bool[maxn];   static void SieveOfEratosthenes(int n)  {    for (int i = 0; i < isPrime.Length; i += 1) {      isPrime[i] = true;    }      for (int p = 2; p * p <= n; p++) {       // If prime[p] is not changed,      // then it is a prime      if (isPrime[p] == true) {         // Update all multiples of P        for (int i = p * p; i <= n; i += p)          isPrime[i] = false;      }    }  }   // Function to find the number of valid permutations  static void countCycles(int m, int n, int prev, int par)  {    // If a complete permutation is formed    if (m==0) {      if (isPrime[prev + 1]) {         // If the sum of 1st and last element        // of the current permutation is prime        ans++;      }      return;    }     // Iterate from par to N    for (int i = 1 + par; i <= n; i++) {       if (!marked[i] && isPrime[i + prev]) {         // Visit the current number        marked[i] = true;         // Recursive Call        countCycles(m - 1, n, i, 1 - par);         // Backtrack        marked[i] = false;      }    }  }   static int countPermutations(int N)  {     // Finding all prime numbers upto 2 * N    SieveOfEratosthenes(2 * N);     // Initializing all values in marked as 0    for (int i = 0; i <marked.Length; i += 1) {      marked[i] = false;    }     // Initial condition    marked[1] = true;     countCycles(N - 1, N, 1, 1);     // Return Answer    return ans;  }   // Driver code  public static void Main(string[] args)  {    int N = 6;    Console.WriteLine(countPermutations(N));   }} // This code is contributed by AnkThon
<script>// Javascript implementation for the above approach // Initialize a global variable Nconst maxn = 100; // Stores the final count of permutationslet ans = 0; // Stores whether the integer is primelet isPrime = new Array(maxn).fill(true);let marked = new Array(maxn).fill(false); function SieveOfEratosthenes(n) {   for (let p = 2; p * p <= n; p++) {     // If prime[p] is not changed,    // then it is a prime    if (isPrime[p] == true) {       // Update all multiples of P      for (let i = p * p; i <= n; i += p)        isPrime[i] = false;    }  }} // Function to find the number of valid permutationsfunction countCycles(m, n, prev, par) {  // If a complete permutation is formed  if (!m) {    if (isPrime[prev + 1]) {       // If the sum of 1st and last element      // of the current permutation is prime      ans++;    }    return;  }   // Iterate from par to N  for (let i = 1 + par; i <= n; i++) {     if (!marked[i] && isPrime[i + prev]) {       // Visit the current number      marked[i] = true;       // Recursive Call      countCycles(m - 1, n, i, 1 - par);       // Backtrack      marked[i] = false;    }  }} function countPermutations(N){   // Finding all prime numbers upto 2 * N  SieveOfEratosthenes(2 * N);    // Initial condition  marked[1] = true;   countCycles(N - 1, N, 1, 1);   // Return Answer  return ans;} // Driver codelet N = 6;document.write(countPermutations(N)); // This code is contributed by gfgking.</script>
2
Time Complexity: O(N!)Auxiliary Space: O(1)
rakeshsahni
29AjayKumar
gfgking
ankthon
simmytarika5
sweetyty
permutation
Prime Number
Backtracking
Combinatorial
Mathematical
Searching
Searching
Mathematical
Prime Number
permutation
Combinatorial
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tug of War
Find if there is a path of more than k length from a source
Difference between Backtracking and Branch-N-Bound technique
N-Queen Problem | Local Search using Hill climbing with random neighbour
Find shortest safe route in a path with landmines
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
Count ways to reach the nth stair using step 1, 2 or 3
Program to calculate value of nCr