Game of Nim with removal of one stone allowed in C++

In this problem called the game of Nim, we are given a positive integer N denoting the pile of stones and there are two players ‘playerA’ and ‘playerB’. Our task is to create a program to predict the winner of the Game of Nim.

GAME OF NIM − We have a heap of stones and two players ‘playerA’ and ‘playerB’. Each player can pick one store from the heap if ‘playerA’ starts picking one stone from the heap. We need to predict the winner of the game. The last player to pick the stone from the heap is the winner of the game.

Let’s take an example to understand the problem

Input: N = 6
Output: playerB
Explanation :
Total stones = 6, players picking stones as
playerA - playerB - playerA - playerB - playerA - playerB

Solution Approach

One method to solve the problem is by finding the general formula for the values of N and the winner of the game. Let’s see some values of N, and the winners in each case,

N = 1, winner = playerA

N = 2, winner = playerB

N = 3, winner = playerA

From this, we can derive that if N is odd, playerA is the winner. And if N is even, playerB is the winner.


Program to illustrate the working of our solution

using namespace std;

bool findGameofNimWinner(int N){
   if(N%2 == 0)
      return 0;
      return 1;
int main(){

   int N = 26;
   cout<<"The winner of the Game of Nim is ";
   findGameofNimWinner(N) ? (cout << "Player A") : (cout << "Player B");
   return 0;


The winner of the Game of Nim is Player B

Updated on: 01-Feb-2022


Kickstart Your Career

Get certified by completing the course

Get Started