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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- 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
- Permutation of first N positive integers such that prime numbers are at prime indices | Set 2
- Permutation of first N positive integers such that prime numbers are at prime indices
- 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 all good indices in the given Array
- Find the GCD of N Fibonacci Numbers with given Indices
- Find the count of unvisited indices in an infinite array
- Find the permutation p from the array q such that q[i] = p[i+1] - p[i]
- Find the possible permutation of the bits of N
- How to find Lexicographically previous permutation?
- Find the maximum value permutation of a graph
- Find permutation with maximum remainder Sum
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.