给定N个硬币,任务是找到谁赢得了硬币游戏。
硬币游戏是一种游戏,其中每个玩家都从给定的N个硬币中挑选硬币,这样他就可以在一轮中选择1到5个硬币,并且游戏对于两个玩家都将继续。选择最后一个硬币的玩家将输掉比赛。
例子:
Input: N = 4
Output: First Player
Explanation:
Player 1 pick 3 coins and
Player 2 pick last coin
Input: N = 7
Output: Second Player
方法:
- 因为玩家可以拿取从1到5(含)之间的硬币,如果一个玩家输了,这意味着他只有1个硬币,否则,他本可以比可用硬币少拿1个硬币,并迫使另一位玩家输掉。因此,现在我们考虑第二个玩家要赢的情况,这意味着第一个玩家只有一个硬币。
- 在N = 1时,第二位玩家将获胜;在N = 2到6之间,第一位玩家可以选择比N少1个硬币,并迫使第二位玩家输掉,因此将其丢弃;对于N = 7,第一位玩家可以选择硬币从1到5,这将留下6到2的硬币,然后第二个玩家可以选择1到5,而赢得第二个玩家将明智地少选择1个硬币,迫使第一枚硬币松动,所以基本上从1开始,所有数字差距为6(无论第一玩家选择什么,第二玩家将选择等于6的差额的硬币,而第一玩家选择的硬币)将成为第二玩家的获胜。
- 最后,我们只需要检查n是否为6 * c + 1形式,则第二位玩家将获胜,否则第一位玩家将获胜。
下面是上述方法的实现:
C++
// C++ program to find the player
// who wins the game
#include
using namespace std;
// Function to check the
// wining player
void findWinner(int n)
{
// As discussed in the
// above approach
if ((n - 1) % 6 == 0) {
cout << "Second Player wins the game";
}
else {
cout << "First Player wins the game";
}
}
// Driver function
int main()
{
int n = 7;
findWinner(n);
}
Java
// Java program to find the player
// who wins the game
class GFG
{
// Function to check the
// wining player
static void findWinner(int n)
{
// As discussed in the
// above approach
if ((n - 1) % 6 == 0)
{
System.out.println("Second Player wins the game");
}
else
{
System.out.println("First Player wins the game");
}
}
// Driver Code
public static void main(String[] args)
{
int n = 7;
findWinner(n);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to find the player
# who wins the game
# Function to check the
# wining player
def findWinner(n):
# As discussed in the
# above approach
if ((n - 1) % 6 == 0):
print("Second Player wins the game");
else:
print("First Player wins the game");
# Driver Code
if __name__ == '__main__':
n = 7;
findWinner(n);
# This code is contributed by 29AjayKumar
C#
// C# program to find the player
// who wins the game
using System;
class GFG
{
// Function to check the
// wining player
static void findWinner(int n)
{
// As discussed in the
// above approach
if ((n - 1) % 6 == 0)
{
Console.WriteLine("Second Player wins the game");
}
else
{
Console.WriteLine("First Player wins the game");
}
}
// Driver Code
public static void Main()
{
int n = 7;
findWinner(n);
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
Second Player wins the game
时间复杂度: