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

C++Server Side ProgrammingProgramming

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
raja
Published on 03-Jul-2021 08:13:03
Advertisements