Game of Stones

Two players called P1 and P2 are playing a game with a starting number of stones. Player 1 always plays first, and the two players move in alternating turns. The game's rules are as follows:

1. In a single move, a player can remove either 2,3, or 5 stones from the game board.

2. If a player is unable to make a move, that player loses the game.

Given the starting number of stones, find and print the name of the winner. P1 is named First and P2 is named Second. Each player plays optimally, meaning they will not make a move that causes them to lose the game if a winning move exists.

Example:

Input:  n = 4
Output: First

Approach

Java

public class GameStones {
    public static void main(String[] args) {

        int n = 4;

        System.out.println(gameOfStones(n));

    }

    static String gameOfStones(int n) {
        if (n % 7 == 0 || n % 7 == 1)
            return "Second";
        return "First";
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

string gameOfStones(int n)
{
    if (n % 7 == 0 || n % 7 == 1)
        return "Second";
    return "First";
}

int main()
{
    int n = 4;

    cout << gameOfStones(n);

    return 0;
}


No comments:

Post a Comment