Program to find winner of a set element removal game in Python

PythonServer Side ProgrammingProgramming

Suppose We have a set of first n natural numbers {1..n}. Amal and Bimal are playing a game.The game rules are like below

  • Amal always plays first

  • During each move, the current player selects a prime number p from the set. The player then removes p and all of its multiples from the set.

  • Whoever has no move will lose the game If we have n, we have to find the winner name.

So, if the input is like n = 5, then the output will be Amal, because the initial set is {1,2,3,4,5}. Now let Amal selects a number p = 2, and removes 2, 4 from the set, so current set is {1,3,5}, there are two primes left, so Bimal may select any of them but there are no remaining elements to remove and finally Amal removes another prime and win the game.

To solve this, we will follow these steps −

  • primes := an array of size 100000, initially all are 0
  • sieve := an array of size 100000, initially all are 0
  • for i in range 2 to 99999, do
    • if sieve[i] is same as 0, then
      • primes[i] := primes[i-1]+1
      • for j in range i to 100000, update in each step by i, do
        • sieve[j] := i
    • otherwise,
      • primes[i] := primes[i-1]
  • From the main method do the following −
  • return "Bimal" if primes[n] is odd otherwise "Amal"


Let us see the following implementation to get better understanding −

primes = [0 for i in range(100001)]
sieve = [0 for i in range(100001)]
for i in range(2, 100000):
   if sieve[i] == 0:
      primes[i] = primes[i-1]+1

      for j in range(i, 100001, i):
         sieve[j] = i
      primes[i] = primes[i-1]

def solve(n):
   return "Bimal" if primes[n] % 2 == 0 else "Amal"

n = 5




Published on 23-Oct-2021 07:33:09