Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K in C++

C++Server Side ProgrammingProgramming

Suppose we have two integers N and K. We have to find a permutation of integers from the range [1 to N] such that the number of indices (1 – base indexing) where gcd(P[i], i) > 1 is exactly K. So if N = 4 and K = 3, then output will be [1, 2, 3, 4], as gcd(1, 1) = 1, gcd(2, 2) = 2, gcd(3, 3) = 3, gcd(4, 4) = 4

If we observe it carefully, we can find that gcd(i, i+1) = 1, gcd(1, i) = 1 and gcd(i, i) = i. As the GCD of any number and 1 is always 1, K can almost be N – 1. Consider the permutation where P[i] = i. Number of indices where gcd(P[i], i) > 1, will be N – 1. If we swap two consecutive elements excluding 1, will reduce the count of such indices by exactly 2, and swapping with 1 will reduce the count by exactly 1.

Example

 Live Demo

#include<iostream>
using namespace std;
void findPermutation(int n, int k) {
   if (k >= n || (n % 2 == 0 && k == 0)) {
      cout << -1;
      return;
   }
   int P[n + 1];
   for (int i = 1; i <= n; i++)
   P[i] = i;  
   int count = n - 1;
   for (int i = 2; i < n; i+=2) {
      if (count - 1 > k) {
         swap(P[i], P[i + 1]);
         count -= 2;
      } else if (count - 1 == k) {
         swap(P[1], P[i]);
         count--;
      } else
         break;
   }
   for (int i = 1; i <= n; i++)
   cout << P[i] << " ";
}
int main() {
   int n = 5, k = 3;
   cout << "Permutation is: ";
   findPermutation(n, k);
}

Output

Permutation is: 2 1 3 4 5
raja
Published on 18-Dec-2019 10:16:56
Advertisements