Program to find out if we win in a game in Python

PythonServer Side ProgrammingProgramming

Suppose we are playing a two-player game where there are n number of marbles and in each round, a player has to take a positive square number of marbles. If a player can't take that square number of marbles, he/she loses. So, given a number n, we have to find out if we can win the game or not. We always make the first turn and select an optimal number of marbles.

So, if the input is like 14, then the output will be True. Because at the first turn, we take 9 marbles. That leaves 5 marbles from which the other player can take a maximum of 4 marbles leaving 1 marble behind. So, in the next turn, we take the last marble leaving 0 marbles behind the opponent can't make a move. Thus, we win.

To solve this, we will follow these steps −

  • if n <= 0, then
    • return False
  • ans := False
  • for i in range integer part of (square root of (n)) to -1, decrease by 1, do
    • if i * i > n, then
      • come out from the loop
    • ans := ans OR (not solve(n - i * i))
    • if ans is True, then
      • return ans
  • return ans

Example

Let us see the following implementation to get better understanding −

from math import sqrt

def solve(n):
   if n <= 0:
      return False
   ans = False
   for i in range(int(sqrt(n)), 0, -1):
      if i * i > n:
         break
      ans = ans | (not solve(n - i * i))
      if ans:
         return ans
   return ans

print(solve(14))

Input

14

Output

True
raja
Published on 16-Oct-2021 11:08:12
Advertisements