- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- 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 find out the minimum moves in a snakes and ladders 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 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 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 Out if There is a Short Circuit in Input Words in Python
- Program to find out if a BST is present in a given binary tree in Python
- Program to find maximum score in stone game in Python