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).
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 contribute@geeksforgeeks.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.