在《尼姆游戏》中,两名玩家轮流从堆或石头堆中移出物体。
假设有两个玩家A和B在玩游戏。每个都只能从堆中取出一块石头。挑选堆最后一块石头的玩家将赢得比赛。给定N堆中的石头数量,如果玩家A开始游戏,则任务是找到获胜者。
例子 :
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
在N = 1的情况下,玩家A会从堆中取出唯一的石头,并赢得比赛。
对于N = 2,玩家A将移除第一块石头,然后玩家B将移除第二块或最后一块石头。因此,玩家B将赢得比赛。
因此,我们可以观察到,当N为奇数时,玩家A获胜,而当N为偶数时,玩家B获胜。
以下是此方法的实现:
C++
// C++ program for Game of Nim with removal
// of one stone allowed.
#include
using namespace std;
// Return true if player A wins,
// return false if player B wins.
bool findWinner(int N)
{
// Checking the last bit of N.
return N&1;
}
// Driven Program
int main()
{
int N = 15;
findWinner(N)? (cout << "Player A";):
(cout << "Player B";);
return 0;
}
Java
// JAVA Code For Game of Nim with
// removal of one stone allowed
import java.util.*;
class GFG {
// Return true if player A wins,
// return false if player B wins.
static int findWinner(int N)
{
// Checking the last bit of N.
return N & 1;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int N = 15;
if(findWinner(N)==1)
System.out.println("Player A");
else
System.out.println("Player B");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 code for Game of Nim with
# removal of one stone allowed.
# Return true if player A wins,
# return false if player B wins.
def findWinner( N ):
# Checking the last bit of N.
return N & 1
# Driven Program
N = 15
print("Player A" if findWinner(N) else "Player B")
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# Code For Game of Nim with
// removal of one stone allowed
using System;
class GFG {
// Return true if player A wins,
// return false if player B wins.
static int findWinner(int N)
{
// Checking the last bit of N.
return N & 1;
}
/* Driver program to test above function */
public static void Main()
{
int N = 15;
if(findWinner(N) == 1)
Console.Write("Player A");
else
Console.Write("Player B");
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
Player A