Counter game

  • + 0 comments
    def counterGame(n):
        turns = 0
        while n > 1:
            # Check if n is a power of 2
            if (n & (n - 1)) == 0:
                # If it's a power of 2, divide by 2
                n >>= 1  # Equivalent to n = n // 2
            else:
                # If not a power of 2, find the largest power of 2 less than n
                # This can be found by taking 2 raised to the power of (n.bit_length() - 1)
                # n.bit_length() gives the number of bits required to represent n,
                # which is equivalent to floor(log2(n)) + 1.
                # So, the largest power of 2 less than n is 2^(floor(log2(n))).
                # We can get this using a bit shift: 1 << (n.bit_length() - 1)
                largest_power_of_2 = 1 << (n.bit_length() - 1)
                n -= largest_power_of_2
            turns += 1
    
        # If the number of turns is odd, Louise wins (since she starts)
        # If the number of turns is even, Richard wins
        if turns % 2 == 1:
            return "Louise"
        else:
            return "Richard"