Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4011e30

Browse files
Create grundy_numbers.cpp
1 parent 1ab2841 commit 4011e30

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎Game Theory/grundy_numbers.cpp‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*Calculate the Grundy Number for the given 'n' in the game.
2+
The game starts with a number- ‘n’ and the player to move divides the number- ‘n’ with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game?
3+
Input Format
4+
An Integer 'n'
5+
Output Format
6+
Grundy Number(n)
7+
Sample Input 1 -
8+
10
9+
Sample Output 1-
10+
0
11+
*/
12+
13+
14+
15+
#include<bits/stdc++.h>
16+
using namespace std;
17+
18+
int mex(int a, int b, int c){
19+
unordered_set<int>s;
20+
s.insert(a);
21+
s.insert(b);
22+
s.insert(c);
23+
for(int i=0; i<max(a, max(b,c))+2; i++){
24+
if(s.count(i)==0)
25+
return i;
26+
}
27+
}
28+
29+
int grundy(int n){
30+
if(n<=0)
31+
return 0;
32+
return mex(grundy(n/2), grundy(n/3), grundy(n/6));
33+
}
34+
int main(){
35+
int n;
36+
cin>>n;
37+
cout<<grundy(n);
38+
return 0;
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /