Take turns taking the stone game

  • Problem Description

Two smart enough people play the game of taking stones in turns. Whoever takes the last stone wins. They can only take 1, 3, 7 or 8 stones at a time. When writing a program to judge n stones, take first. Of people are winning or losing.

Input format:
an integer n whose value does not exceed 10000000.
Output format:
If the person who takes first wins, please output 1 in a single line, otherwise output 0.

Input sample:
Here are 3 groups of input.

1
10
300

Output sample:
The output corresponding to the above three sets of data are as follows:

1
1
0
  • Problem interpretation

First of all, these two people are smart enough. If the first person takes first, he will try his best to win. But the second person is not a vegetarian, he will spare no effort to prevent the first person from winning. Since the number of stones is uncertain, we might as well try the water with a smaller number of stones first to see if we can find a pattern.

  • Enumeration analysis

We assume that P 1 P_1P1 P 2 P_2 P2It represents the first person and the second person respectively, and the first person takes first. Now let's enumerate several situations and see under what circumstances the first person will win.

A stone:

Insert picture description here

Note: The first person wins.

Two stones:

Insert picture description here

Note: The first person loses.

Three stones:

The first situation:

Insert picture description here

Note: The first person wins.

The second case:

Insert picture description here

Note: The first person wins.

Four stones:

The first situation:

Insert picture description here

Note: The first person wins.

The second case:

Insert picture description here

Note: The first person wins.

Five stones:

The first situation:

Insert picture description here

Note: The first person wins.

The second case:

Insert picture description here

Note: The first person wins.

The third case:

Insert picture description here

Note: The first person wins.

Continue to enumerate and find that when the number of stones is: 2 4 6 15 17 19 30 32 34 36 45 47 49 51..., the second person wins. Observing these data, we can find that when n%15==0 or 2 or 4 or 6, the second person wins, and the first person wins in other situations. In this way, we have found the law.

  • Code

#include<iostream>
using namespace std;
int main()
{
    
    
	int n;
	while(cin>>n)
	{
    
    
	    if(n%15==0)
            cout<<0;
        else if(n%15==2)
            cout<<0;
        else if(n%15==4)
            cout<<0;
        else if(n%15==6)
            cout<<0;
        else
            cout<<1;
	}
	return 0;
}
  • operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46308522/article/details/110544498