Find permutation of first N natural numbers that satisfies the given condition
Last Updated :
07 Jun, 2022
Given two integer N and K, the task is to find the permutation P of first N natural numbers such that there are exactly K elements which satisfies the condition GCD(P[i], i) > 1 for all 1 ? i ? N.
Examples:
Input: N = 3, K = 1
Output: 2 1 3
GCD(P[1], 1) = GCD(2, 1) = 1
GCD(P[2], 2) = GCD(1, 2) = 1
GCD(P[3], 3) = GCD(3, 3) = 3
There is exactly 1 element such that GCD(P[i], i) > 1
Input: N = 5, K = 2
Output: 3 1 2 4 5
Approach: Keep the last K elements in their place. The rest of the elements are moved such that ith element is placed in (i + 1)th position and (N – K)th element is kept in position 1 because gcd(x, x + 1) = 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void Permutation( int n, int k)
{
int p[n + 1];
for ( int i = 1; i <= n; i++)
p[i] = i;
for ( int i = 1; i < n - k; i++)
p[i + 1] = i;
p[1] = n - k;
for ( int i = 1; i <= n; i++)
cout << p[i] << " " ;
}
int main()
{
int n = 5, k = 2;
Permutation(n, k);
return 0;
}
|
Java
class GFG
{
static void Permutation( int n, int k)
{
int [] p = new int [n + 1 ];
for ( int i = 1 ; i <= n; i++)
p[i] = i;
for ( int i = 1 ; i < n - k; i++)
p[i + 1 ] = i;
p[ 1 ] = n - k;
for ( int i = 1 ; i <= n; i++)
System.out.print(p[i] + " " );
}
public static void main(String[] args)
{
int n = 5 , k = 2 ;
Permutation(n, k);
}
}
|
Python3
def Permutation(n, k):
p = [ 0 for i in range (n + 1 )]
for i in range ( 1 , n + 1 ):
p[i] = i
for i in range ( 1 , n - k):
p[i + 1 ] = i
p[ 1 ] = n - k
for i in range ( 1 , n + 1 ):
print (p[i], end = " " )
if __name__ = = '__main__' :
n = 5
k = 2
Permutation(n, k)
|
C#
using System;
class GFG
{
static void Permutation( int n, int k)
{
int [] p = new int [n + 1];
for ( int i = 1; i <= n; i++)
p[i] = i;
for ( int i = 1; i < n - k; i++)
p[i + 1] = i;
p[1] = n - k;
for ( int i = 1; i <= n; i++)
Console.Write(p[i] + " " );
}
static public void Main ()
{
int n = 5, k = 2;
Permutation(n, k);
}
}
|
PHP
<?php
function Permutation( $n , $k )
{
$p = array ();
for ( $i = 1; $i <= $n ; $i ++)
$p [ $i ] = $i ;
for ( $i = 1; $i < $n - $k ; $i ++)
$p [ $i + 1] = $i ;
$p [1] = $n - $k ;
for ( $i = 1; $i <= $n ; $i ++)
echo $p [ $i ], " " ;
}
$n = 5; $k = 2;
Permutation( $n , $k );
?>
|
Javascript
<script>
function Permutation(n, k)
{
let p = new Array(n + 1);
for (let i = 1; i <= n; i++)
p[i] = i;
for (let i = 1; i < n - k; i++)
p[i + 1] = i;
p[1] = n - k;
for (let i = 1; i <= n; i++)
document.write(p[i] + " " );
}
let n = 5, k = 2;
Permutation(n, k);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...