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.
Input : N = 3. Output : Player A 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:
Time Complexity: O(1).
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Divisibility by 64 with removal of bits allowed
- Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
- Game Theory (Normal - form game) | Set 1 (Introduction)
- Combinatorial Game Theory | Set 2 (Game of Nim)
- A modified game of Nim
- Implementation of Tic-Tac-Toe game
- Variation in Nim Game
- Check if the game is valid or not
- Optimal Strategy for a Game | DP-31
- Find the winner in nim-game
- Optimal Strategy for a Game | Set 3
- Predict the winner in Coin Game
- Count the numbers that can be reduced to zero or less in a game
- Game of replacing array elements
- Game Development with Unity | Introduction
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : vt_m