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 plays 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.

To solve this, we will follow these steps −

  • if target % (k + 1) is not 0, then
    • return true
  • otherwise
    • return false

Example

Let us see the following implementation to get better understanding −

def solve(k, target):
   return target % (k + 1) != 0

k = 5
target = 10
print(solve(k, target))

Input

5, 10

Output

True

Updated on: 18-Oct-2021

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements