
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Good Permutation of First N Natural Numbers in C++
In this problem, we are an integer value N. Our task is to find the good permutation of first N natural numbers.
permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement.
Good Permutation is a permutation in which $1\leqslant{i}\leqslant{N}$ and follows,
$P_{pi}\:=\:i$
$P_{p!}\:=\:i$
Let's take an example to understand the problem,
Input : N = 1 Output : -1
Solution Approach
A simple solution to the problem is by finding permutations p such that pi = i.
Then we will reconsider the equation to satisfy pi != i. So, for a value x such that $2x \leqslant x$, we have p2x - 1 and p2k. Now, we have an equation that satisfies the permutation equation for n. Here, the solution for the equation.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; void printGoodPermutation(int n) { if (n % 2 != 0) cout<<-1; else for (int i = 1; i <= n / 2; i++) cout<<(2*i)<<"\t"<<((2*i) - 1)<<"\t"; } int main() { int n = 4; cout<<"Good Permutation of first N natural Numbers : \n"; printGoodPermutation(n); return 0; }
Output
Good Permutation of first N natural Numbers : 2 1 4 3
Advertisements