- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

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

- if i * i > n, then
- 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

- Related Articles
- Program to find number of moves to win deleting repeated integer game in Python
- Program to find out the maximum points collectable in a game in Python
- Program to find number of expected moves required to win Lotus and Caterpillar game in Python
- Program to check whether Amal can win stone game or not in Python
- Program to find number of possible moves to start the game to win by the starter in Python
- Program to find out the minimum moves in a snakes and ladders game in Python
- Program to check whether first player win in candy remove game or not in Python?
- Program to find maximum score we can get in jump game in Python
- Minimum Players required to win the game in C++
- Program to check person 1 can win the candy game by taking maximum score or not in Python
- Program to find winner of stone game in Python
- Program to find winner of a rower reducing game in Python
- Program to find winner of a rower breaking game in Python
- Program to find maximum score in stone game in Python
- Program to find winner of array removal game in Python