Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check first player can win by reaching total sum to target in Python
Suppose we have two numbers k and target. Now consider Amal and Bimal are playing a game. In each round, Amal picks a number from 1 to k to add to the total score that initially starts from 0. Whoever crosses the total to target wins. Amal always plays first, we have to check whether he can force a win if both of them play optimally.
So, if the input is like k = 5, target = 10, then the output will be True, as if Amal picks 4 first, then whether Bimal picks 1, 2, ..., or 5, Amal can always reach 10 by picking 5 next.
Algorithm
To solve this, we will follow these steps −
- if target % (k + 1) is not 0, then
- return True
- otherwise
- return False
How It Works
The key insight is that if target % (k + 1) == 0, then the second player (Bimal) can always mirror the first player's moves to maintain winning positions. If the remainder is non-zero, the first player (Amal) can force a win by making strategic moves.
Example
Let us see the following implementation to get better understanding −
def solve(k, target):
return target % (k + 1) != 0
k = 5
target = 10
result = solve(k, target)
print(f"Can first player win? {result}")
print(f"Calculation: {target} % ({k} + 1) = {target % (k + 1)}")
The output of the above code is −
Can first player win? True Calculation: 10 % (5 + 1) = 4
Another Example
Let's test with a case where the first player cannot win −
def solve(k, target):
return target % (k + 1) != 0
# Test case where first player cannot win
k = 4
target = 15
result = solve(k, target)
print(f"k = {k}, target = {target}")
print(f"Can first player win? {result}")
print(f"Calculation: {target} % ({k} + 1) = {target % (k + 1)}")
The output of the above code is −
k = 4, target = 15 Can first player win? True Calculation: 15 % (4 + 1) = 0
Conclusion
The first player can win if target % (k + 1) != 0. This mathematical approach provides an optimal solution in O(1) time complexity by identifying winning and losing positions based on game theory principles.
