Predict the winner in Coin Game in C++

C++Server Side ProgrammingProgramming

In this game, there are two players X and Y. our task is to predict who will win the game if both play optimally and X starts the game.

Game

In the coin game, there are two piles with N and M number of coins. One of the players chooses any one of the piles for the game. Then the task is to divide the piles into two halves till any one player cannot further divide the piles.

Let’s take an example to understand the problem,

Input: M = 2 , N = 2
Output:X

Explanation - X starts the game and choose M pile(both are same), and divide the pile into two. Now each will contain only one coin, so Y will be left with no move. This will make X win.

To solve this problem, we need to see the chances that player X wins. The case in which player X wins is when any of the piles will have an even number of coins. Otherwise, Y will be the winner.

Program to show the implementation of our logic

Example

 Live Demo

#include <iostream>
using namespace std;
int isXWinner(int M, int N) {
   if (M % 2 == 0 || N % 2 == 0)
   return 1;
   return 0;
}
int main() {
   int M = 1, N = 2;
   cout<<"Game Starts!\n";
   if(isXWinner(M,N))
      cout<<"Player X is the Winner";
   else
      cout<<"Player Y is the Winner";
   return 0;
}

Output

Game Starts!
Player X is the Winner
raja
Published on 04-Feb-2020 07:20:58
Advertisements