Nim Game

Posted on


You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.


Coding part is easy. Just justify whether n is one integer multiples of 4.

return n % 4 != 0;

According to the problem’s prototypes, when n = 1, 2, 3, the first goer can definitely win; when n = 4, the first goer will lose. Think about why first goer with 4 stones will definitely lose. Because players are free minded, the second goer can adjust the move following the first one. He will try everything to leave 4 stones to the first goer. So any multiples of 4 equals to n = 4 case.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s