VOOZH about

URL: https://www.geeksforgeeks.org/dsa/game-nim-removal-one-stone-allowed/

⇱ Game of Nim with removal of one stone allowed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Game of Nim with removal of one stone allowed

Last Updated : 8 May, 2023

In Game of Nim, two players take turns removing objects from heaps or the pile of stones. 
Suppose two players A and B are playing the game. Each is allowed to take only one stone from the pile. The player who picks the last stone of the pile will win the game. Given N the number of stones in the pile, the task is to find the winner, if player A starts the game.
Examples : 
 

Input : N = 3.
Output : Player A

👁 Image

Player A remove stone 1 which is at the top, then Player B remove stone 2 
and finally player A removes the last stone.

Input : N = 15.
Output : Player A

For N = 1, player A will remove the only stone from the pile and wins the game. 
For N = 2, player A will remove the first stone and then player B remove the second or the last stone. So player B will win the game.
So, we can observe player A wins when N is odd and player B wins when N is even.
Below is the implementation of this approach: 
 

Output : 
 

Player A


Time Complexity: O(1).

Auxiliary Space: O(1)


 

Comment
Article Tags: