📜  允许移除一颗石头的尼姆游戏

📅  最后修改于: 2021-09-24 03:20:56             🧑  作者: Mango

在尼姆游戏中,两名玩家轮流从堆或石堆中取出物体。
假设两个玩家 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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程