- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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.

#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); }

The permutation is: 3 1 2 4 5

- Related Questions & Answers
- 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
- 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++
- PHP program to find the average of the first n natural numbers that are even
- 8085 program to find the sum of first n natural numbers
- Sum of first n natural numbers in C Program
- Average of first n even natural numbers?
- Sum of sum of first n natural numbers in C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- C Program for the cube sum of first n natural numbers?
- Count all possible N digit numbers that satisfy the given condition in C++
- PHP program to find the sum of cubes of the first n natural numbers

Advertisements