C++ code to find minimum number starting from n in a game


Suppose we have a number n. In a game initially the value of n is v and the player is able to do the following operation zero or more times: Select a positive integer x that x < n and x is not a divisor of n, then subtract x from n. The goal of the player is to minimize the value of n in the end.

So, if the input is like n = 8, then the output will be 1, because the player can select x = 3 in the first turn, then n becomes 5. We can then choose x = 4 in the second turn to get n = 1 as the result.

Steps

To solve this, we will follow these steps −

if n is same as 2, then:
   return 2
return 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int n){
   if (n == 2){
      return 2;
   }
   return 1;
}
int main(){
   int n = 8;
   cout << solve(n) << endl;
}

Input

8

Output

1

Updated on: 29-Mar-2022

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements