Counter game

  • + 0 comments

    C# solution with comments:

    public static string counterGame(long n)

        {
    
                bool currentPlayer1 = true;
    
    
        while(n > 1)
        {   
            // Check if n is a power of 2
            //A number is a power of 2 if it has exactly one 1 bit in its binary representation. (i.e. 100)         
            if((n & (n - 1)) == 0)
            {
                n = n/2;             
            }
            else
            {             
                //Math.Log(n, 2) -  Math.Log(20, 2) will return approximately 4.32 because 2 4.32 = 20
                //Math.Floor(4.32) round down, so will produce 4.
                //Math.Pow(2, 4) which will produce 16
                //So finally 20 - 16, will give 4, which will be the new number for the next turn.
                long largestPowerOf2 = (long)Math.Pow(2, (long)Math.Floor(Math.Log(n, 2)));
                n -= largestPowerOf2;                                
            }
    
            currentPlayer1 = !currentPlayer1;
    
        }
    
        return currentPlayer1 ? "Richard" : "Louise";
    }