Game of Nim with removal of one stone allowed
Last Updated :
08 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
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:
C++
#include<bits/stdc++.h>
using namespace std;
bool findWinner( int N)
{
return N&1;
}
int main()
{
int N = 15;
findWinner(N)? (cout << "Player A" ;):
(cout << "Player B" ;);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int findWinner( int N)
{
return N & 1 ;
}
public static void main(String[] args)
{
int N = 15 ;
if (findWinner(N)== 1 )
System.out.println( "Player A" );
else
System.out.println( "Player B" );
}
}
|
Python3
def findWinner( N ):
return N & 1
N = 15
print ( "Player A" if findWinner(N) else "Player B" )
|
C#
using System;
class GFG {
static int findWinner( int N)
{
return N & 1;
}
public static void Main()
{
int N = 15;
if (findWinner(N) == 1)
Console.Write( "Player A" );
else
Console.Write( "Player B" );
}
}
|
PHP
<?php
function findWinner( $N )
{
return $N &1;
}
$N = 15;
if (findWinner( $N ))
echo "Player A" ;
else
echo "Player B" ;
?>
|
Javascript
<script>
function findWinner(N)
{
return N & 1;
}
let N = 15;
if (findWinner(N)==1)
document.write( "Player A" );
else
document.write( "Player B" );
</script>
|
Output :
Player A
Time Complexity: O(1).
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...