# Program to check whether Amal can win stone game or not in Python

Suppose there are two players Amal and Bimal, they are playing a game, and with Amal starts first. Initially, there are n different stones in a pile. On each player's turn, he makes a move consisting of removing any square number (non-zero) of stones from the pile. Also, if one player is unable to make a move, he loses the game. So if we have n, we have to check whether Amal can win the game or not.

So, if the input is like n = 21, then the output will be True because at first Amal can take 16, then Bimal takes 4, then Amal takes 1 and wins the game.

To solve this, we will follow these steps −

• squares := a new list

• square := 1

• increase := 3

• while square <= n, do

• insert square at the end of squares

• square := square + increase

• increase := increase + 2

• insert square at the end of squares

• dp := a blank list of size (n + 1)

• dp := False

• for k in range 1 to n, do

• s := 0

• dp[k] := False

• while squares[s] <= k and dp[k] is empty, do

• if dp[k - squares[s]] is empty, then

• dp[k] := True

• s := s + 1

• return last element of dp

## Example

Let us see the following implementation to get better understanding

def solve(n):
squares = []
square = 1
increase = 3
while square <= n:
squares.append(square)
square += increase
increase += 2
squares.append(square)

dp = [None] * (n + 1)
dp = False
for k in range(1, n + 1):
s = 0
dp[k] = False
while squares[s] <= k and not dp[k]:
if not dp[k - squares[s]]:
dp[k] = True
s += 1
return dp[-1]

n = 21
print(solve(n))

## Input

21


## Output

True