A number N will be given to you, you need to tell total number of permutation ?

0 votes

This problem is popularly known as derangement problem.

The explanation is given below -

Suppose that there are n persons numbered 1, 2, ..., n. Let there be n hats also numbered 1, 2, ..., n. We have to find the number of ways in which no one gets the hat having same number as his/her number.

Let us assume that the first person takes hat i. There are n - 1 ways for the first person to make such a choice. There are now two possibilities, depending on whether or not person i takes hat 1.

In this way you can derive a recurrence relation for same.

Read more about that at - https://en.wikipedia.org/wiki/Derangement

Now you can write code as below -

#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; int der[N + 1]; der[0] = 1; der[1] = 0; der[2] = 1; for (int i = 3; i <= N; ++i) { der[i] = (i - 1)*(der[i - 1] + der[i - 2]); } cout << der[N] << endl; }

...