Number of moves required to guess a permutation in C++


Given a number N, we need to find the moves required to guess the permutation in the worst-case scenario. The number of moves required to guess the permutation will be n!. Let's take an example.

Input

5

Output

129

When we have 5 elements, then we have 5 ways to guess, and 4 ways when we have 4 elements and it continuous till 1.

Algorithm

  • Initialise the number n.
  • Initialise count to 1.
  • Write a loop that iterates from 1 to n.
    • Multiply count with the current number.
  • Return the count.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getNumberMoves(int n) {
   int count = 0;
   for (int i = 1; i <= n; i++) {
      count += i * (n - i);
   }
   count += n;
   return count;
}
int main() {
   int n = 9;
   cout << getNumberMoves(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

129

Updated on: 26-Oct-2021

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements