Given two integers N and K, the task is to find a permutation of integers from the range [1, N] such that the number of indices (1-based indexing) where gcd(p[i], i) > 1 is exactly K. Print -1 if such permutation is not possible.
Input: N = 4, K = 3
Output: 1 2 3 4
gcd(1, 1) = 1
gcd(2, 2) = 2
gcd(3, 3) = 3
gcd(4, 4) = 4
Therefore, there are exactly 3 indices where gcd(p[i], i) > 1
Input: N = 1, K = 1
Approach: A couple of observations can be made here:
- gcd(i, i + 1) = 1
- gcd(1, i) = 1
- gcd(i, i) = i
Since, gcd of 1 with any other number is always going to be one, K can atmost be N – 1. Consider the permutation where p[i] = i, The number of indices where gcd(p[i], i) > 1 will be N – 1. Notice that swapping 2 continuous elements (excluding 1) will reduce the count of such indices by exactly 2. And swapping with 1 will reduce the count by exactly 1.
Below is the implementation of the above approach:
1 2 3 4
Time Complexity: O(N)
- Number of valid indices in the permutation of first N natural numbers
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Find smallest permutation of given number
- Minimum number of given operations required to convert a permutation into an identity permutation
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
- Find the GCD of N Fibonacci Numbers with given Indices
- Find all good indices in the given Array
- Find the count of unvisited indices in an infinite array
- Find the possible permutation of the bits of N
- Find the permutation p from the array q such that q[i] = p[i+1] - p[i]
- Find permutation with maximum remainder Sum
- Find the minimum permutation of A greater than B
- Find the maximum value permutation of a graph
- How to find Lexicographically previous permutation?
- Find a permutation of 2N numbers such that the result of given expression is exactly 2K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.