- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements