- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find permutation of first N natural numbers that satisfies the given condition in C++

Suppose we have two integers N and K, and we have 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. So when N = 3 and K = 1, then output will be 2, 1, 3. And gcd(2, 1) = 1, gcd(1, 2) = 1, gcd(3, 3) = 3

The approach is simple, we will keep the last k elements in their place, the rest of the elements are moved, such that ith element will be placed in (i + 1)th position and (N - K)th element is kept in position 1, because gcd(x, x+1) = 1.

## Example

#include<iostream> using namespace std; void findPermutation(int n, int k) { int permutation[n + 1]; for (int i = 1; i <= n; i++) permutation[i] = i; for (int i = 1; i < n - k; i++) permutation[i + 1] = i; permutation[1] = n - k; for (int i = 1; i <= n; i++) cout << permutation[i] << " "; } int main() { int n = 5, k = 2; cout << "The permutation is: "; findPermutation(n, k); }

## Output

The permutation is: 3 1 2 4 5

- Related Articles
- Find the good permutation of first N natural numbers C++
- Find the average of first N natural numbers in C++
- Find if given number is sum of first n natural numbers in C++
- Maximum size of sub-array that satisfies the given condition in C++
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M in Python
- Program to find number of magic sets from a permutation of first n natural numbers in Python
- Maximum size of sub-array that satisfies the given condition in C++ program
- Program to find sum of first n natural numbers in C++
- Find m-th summation of first n natural numbers in C++
- Find the sum of first $n$ odd natural numbers.
- Sum of first n natural numbers in C Program
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- PHP program to find the average of the first n natural numbers that are even
- Count all possible N digit numbers that satisfy the given condition in C++
- Sum of sum of first n natural numbers in C++

Advertisements