We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Counter game
- Discussions
Counter game
Counter game
Sort by
recency
|
184 Discussions
|
Please Login in order to post a comment
this is the solution for java 8 the hardest work was to handle the execution time
Casting the return of Math.Log to float seemed to have better performance than using MathF functions. Once the log is an integer, then whether the log is odd or even determines the winner. Of course, using binary operations may offer improvement as well, but I'm going for the easiest to read solution that is still somewhat efficient. The logical flow is not optimized and is rather a reflection of how I am thinking through the problem.
Louise and Richard's numbers game is an interesting problem involving powers of 2. To determine the winner, you need to follow these steps:
Check if the number 𝑛 n is a power of 2. If it is, divide it by 2. If it's not, subtract the largest power of 2 less than 𝑛 n. Alternate turns between Louise and Richard until the number becomes 1. Let’s walk through the provided example:
For
𝑛
6 n=6:
Louise sees that 6 is not a power of 2. The largest power of 2 less than 6 is 4. So, she subtracts 4 from 6, leaving 2, and passes the turn to Richard. Richard notices that 2 is a power of 2, so he divides it by 2, resulting in 1. If you’re interested in gaming strategies, you might also find it useful to explore other fun and strategic games. For example, check out how to get coins in Car Parking Multiplayer to enhance your gaming experience.
Hope this helps!
He wins the game since reaching 1 means the player who made the move wins. The function can be implemented to repeat these steps for any initial number and determine the winner based on who makes the final move. For the sample input of 6, Richard wins as shown.
It took quiet a time to figure out the solution for me and here is my solution:
But I am amazed by others solution, it is just and understanding of binary theory.
public static String counterGame(long n) { int counter = 0; while(n > 1) { int power =(int)(Math.log(n) / Math.log(2)); if(Math.pow(2,power) != n) n = n - (long)Math.pow(2,power); else n = n/2; counter++; } return (counter % 2 == 0) ? "Richard" : "Louise"; }