Combinatorial Game Theory | Set 3 (Grundy Numbers/Numbers and Mex)
Last Updated :
23 Jul, 2025
We have introduced Combinatorial Game Theory in Set 1 and discussed Game of Nim in Set 2.
Grundy Number is a number that defines a state of a game. We can define any impartial game (example : nim game) in terms of Grundy Number.
Grundy Numbers or Numbers determine how any Impartial Game (not only the Game of Nim) can be solved once we have calculated the Grundy Numbers associated with that game using Sprague-Grundy Theorem.
But before calculating Grundy Numbers, we need to learn about another term- Mex.
What is Mex?
‘Minimum excludant’ a.k.a ‘Mex’ of a set of numbers is the smallest non-negative number not present in the set.

How to calculate Grundy Numbers?
We use this definition- The Grundy Number/ number is equal to 0 for a game that is lost immediately by the first player and is equal to Mex of the numbers of all possible next positions for any other game.
Below are three example games and programs to calculate Grundy Number and Mex for each of them. Calculation of Grundy Numbers is done basically by a recursive function called as calculateGrundy() function which uses calculateMex() function as its sub-routine.
Example 1
The game starts with a pile of n stones, and the player to move may take any positive number of stones. Calculate the Grundy Numbers for this game. The last player to move wins. Which player wins the game?
Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0
If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stones
Hence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]
Similarly, If a player has 2 stones, then he can take only 1 stone or he can take all the stones and wins. So the next possible position of the game (for the other player) is (1, 0) stones respectively.
Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]
Similarly, If a player has 'n' stones, then he can take only 1 stone, or he can take 2 stones........ or he can take all the stones and win. So the next possible position of the game (for the other player) is (n-1, n-2,....1) stones respectively.
Hence, Grundy(n) = Mex (0, 1, 2, ....n-1) = n [According to the definition of Mex]
We summarize the first the Grundy Value from 0 to 10 in the below table-
C++
/* A recursive C++ program to find Grundy Number for
a game which is like a one-pile version of Nim.
Game Description : The game starts with a pile of n stones,
and the player to move may take any positive number of stones.
The last player to move wins. Which player wins the game? */
#include<bits/stdc++.h>
using namespace std;
// A Function to calculate Mex of all the values in
// that set.
int calculateMex(unordered_set<int> Set)
{
int Mex = 0;
while (Set.find(Mex) != Set.end())
Mex++;
return (Mex);
}
// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
int calculateGrundy(int n)
{
if (n == 0)
return (0);
unordered_set<int> Set; // A Hash Table
for (int i=0; i<=n-1; i++)
Set.insert(calculateGrundy(i));
return (calculateMex(Set));
}
// Driver program to test above functions
int main()
{
int n = 10;
printf("%d", calculateGrundy(n));
return (0);
}
Java
// A recursive Java program to find Grundy
// Number for a game which is like a
// one-pile version of Nim. Game
// Description : The game starts
// with a pile of n stones, and the
// player to move may take any
// positive number of stones.
// The last player to move wins.
// Which player wins the game?
import java.util.*;
class GFG{
// A Function to calculate Mex of all
// the values in that set.
public static int calculateMex(Set<Integer> Set)
{
int Mex = 0;
while (Set.contains(Mex))
Mex++;
return (Mex);
}
// A function to Compute Grundy Number
// of 'n'. Only this function varies
// according to the game
public static int calculateGrundy(int n)
{
if (n == 0)
return (0);
// A Hash Table
Set<Integer> Set = new HashSet<Integer>();
for(int i = 0; i <= n - 1; i++)
Set.add(calculateGrundy(i));
return (calculateMex(Set));
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.print(calculateGrundy(n));
}
}
// This code is contributed by divyeshrabadiya07
Python3
''' A recursive Python3 program to find Grundy Number for
a game which is like a one-pile version of Nim.
Game Description : The game starts with a pile of n stones,
and the player to move may take any positive number of stones.
The last player to move wins. Which player wins the game? '''
# A Function to calculate Mex of all the values in
# that set.
def calculateMex(Set):
Mex = 0
while (Mex in Set):
Mex += 1
return (Mex)
# A function to Compute Grundy Number of 'n'
# Only this function varies according to the game
def calculateGrundy( n):
if (n == 0):
return (0)
Set = set() # A Hash Table
for i in range(n):
Set.add(calculateGrundy(i));
return (calculateMex(Set))
# Driver program to test above functions
n = 10;
print(calculateGrundy(n))
# This code is contributed by ANKITKUMAR34
C#
// A recursive C# program to find Grundy
// Number for a game which is like a
// one-pile version of Nim. Game
// Description : The game starts
// with a pile of n stones, and
// the player to move may take
// any positive number of stones.
// The last player to move wins.
// Which player wins the game?
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// A Function to calculate Mex of all
// the values in that set.
static int calculateMex(HashSet<int> Set)
{
int Mex = 0;
while (Set.Contains(Mex))
Mex++;
return (Mex);
}
// A function to Compute Grundy Number
// of 'n'. Only this function varies
// according to the game
static int calculateGrundy(int n)
{
if (n == 0)
return (0);
// A Hash Table
HashSet<int> Set = new HashSet<int>();
for(int i = 0; i <= n - 1; i++)
Set.Add(calculateGrundy(i));
return (calculateMex(Set));
}
// Driver code
public static void Main(string []arg)
{
int n = 10;
Console.Write(calculateGrundy(n));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// A recursive javascript program to find Grundy
// Number for a game which is like a
// one-pile version of Nim. Game
// Description : The game starts
// with a pile of n stones, and the
// player to move may take any
// positive number of stones.
// The last player to move wins.
// Which player wins the game?
// A Function to calculate Mex of all
// the values in that set.
function calculateMex( Set) {
var Mex = 0;
while (Set.has(Mex))
Mex++;
return (Mex);
}
// A function to Compute Grundy Number
// of 'n'. Only this function varies
// according to the game
function calculateGrundy(n) {
if (n == 0)
return (0);
// A Hash Table
var set = new Set();
for (i = 0; i <= n - 1; i++)
set.add(calculateGrundy(i));
return (calculateMex(set));
}
// Driver code
var n = 10;
document.write(calculateGrundy(n));
// This code contributed by aashish1995
</script>
Output :
10
The above solution can be optimized using Dynamic Programming as there are overlapping subproblems.
Example 2
The game starts with a pile of n stones, and the player to move may take any positive number of stones up to 3 only. The last player to move wins. Which player wins the game? This game is 1 pile version of Nim.
Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0
If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stones
Hence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]
Similarly, if a player has 2 stones, then he can take only 1 stone or he can take 2 stones and win. So the next possible position of the game (for the other player) is (1, 0) stones respectively.
Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]
Similarly, Grundy(3) = Mex(0, 1, 2) = 3 [According to the definition of Mex]
But what about 4 stones ?
If a player has 4 stones, then he can take 1 stone or he can take 2 stones or 3 stones, but he can’t take 4 stones (see the constraints of the game). So the next possible position of the game (for the other player) is (3, 2, 1) stones respectively.
Hence, Grundy(4) = Mex (1, 2, 3) = 0 [According to the definition of Mex]
So we can define Grundy Number of any n >= 4 recursively as-
Grundy(n) = Mex[Grundy (n-1), Grundy (n-2), Grundy (n-3)]
We summarize the first the Grundy Value from 0 to 10 in the below table-
C++
/* A recursive C++ program to find Grundy Number for
a game which is one-pile version of Nim.
Game Description : The game starts with a pile of
n stones, and the player to move may take any
positive number of stones up to 3 only.
The last player to move wins. */
#include<bits/stdc++.h>
using namespace std;
// A Function to calculate Mex of all the values in
// that set.
// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
int calculateGrundy(int n)
{
if (n == 0)
return (0);
if (n == 1)
return (1);
if (n == 2)
return (2);
if (n == 3)
return (3);
else
return (n%(3+1));
}
// Driver program to test above functions
int main()
{
int n = 10;
printf("%d", calculateGrundy(n));
return (0);
}
Java
/* A recursive Java program to find
Grundy Number for a game which is
one-pile version of Nim.
Game Description : The game starts with
a pile of n stones, and the player to
move may take any positive number of stones
up to 3 only.The last player to move wins. */
import java.util.*;
class GFG
{
// A function to Compute Grundy
// Number of 'n' Only this function
// varies according to the game
static int calculateGrundy(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 3;
else
return (n%(3+1));
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.printf("%d", calculateGrundy(n));
}
}
// This code is contributed by rahulnamdevrn27
Python3
# A recursive Python3 program to find Grundy Number
# for a game which is one-pile version of Nim.
# Game Description : The game starts with a pile
# of n stones, and the player to move may take
# any positive number of stones up to 3 only.
# The last player to move wins.
# A function to Compute Grundy Number of 'n'
# Only this function varies according to the game
def calculateGrundy(n):
if 0 <= n <= 3:
return n
else:
return (n%(3+1));
# Driver program to test above functions
if __name__ == "__main__":
n = 10
print(calculateGrundy(n))
# This code is contributed by rahulnamdevrn27
C#
/* A recursive Java program to find Grundy Number
for a game which is one-pile version of Nim.
Game Description : The game starts with a pile of
n stones, and the player to move may take any
positive number of stones up to 3 only.The last
player to move wins. */
using System;
using System.Collections.Generic;
class GFG
{
// A function to Compute Grundy Number of
// 'n' Only this function varies according
// to the game
static int calculateGrundy(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 3;
else
return (n%(3+1));
}
// Driver code
public static void Main(String[] args)
{
int n = 10;
Console.Write(calculateGrundy(n));
}
}
// This code is contributed by rahulnamdevrn27
JavaScript
<script>
/* A recursive Javascript program to find
Grundy Number for a game which is
one-pile version of Nim.
Game Description : The game starts with
a pile of n stones, and the player to
move may take any positive number of stones
up to 3 only.The last player to move wins. */
// A function to Compute Grundy
// Number of 'n' Only this function
// varies according to the game
function calculateGrundy(n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 3;
else
return (n % (3 + 1));
}
// Driver code
let n = 10;
document.write(calculateGrundy(n));
// This code is contributed by rag2127
</script>
Output :
2
Example 3
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?
We summarize the first the Grundy Value from 0 to 10 in the below table:

Think about how we generated this table.
C++
/* A recursive C++ program to find Grundy Number for
a game.
Game Description: 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. */
#include<bits/stdc++.h>
using namespace std;
// A Function to calculate Mex of all the values in
// that set.
int calculateMex(unordered_set<int> Set)
{
int Mex = 0;
while (Set.find(Mex) != Set.end())
Mex++;
return (Mex);
}
// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
int calculateGrundy (int n)
{
if (n == 0)
return (0);
unordered_set<int> Set; // A Hash Table
Set.insert(calculateGrundy(n/2));
Set.insert(calculateGrundy(n/3));
Set.insert(calculateGrundy(n/6));
return (calculateMex(Set));
}
// Driver program to test above functions
int main()
{
int n = 10;
printf("%d", calculateGrundy (n));
return (0);
}
Java
/* A recursive Java program to find Grundy Number for
a game.
Game Description : 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. */
import java.util.*;
class GFG
{
// A Function to calculate Mex of all the values in
// that set.
static int calculateMex(HashSet<Integer> Set)
{
int Mex = 0;
while (Set.contains(Mex))
{
Mex++;
}
return (Mex);
}
// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
static int calculateGrundy(int n)
{
if (n == 0)
{
return (0);
}
HashSet<Integer> Set = new HashSet<Integer>(); // A Hash Table
Set.add(calculateGrundy(n / 2));
Set.add(calculateGrundy(n / 3));
Set.add(calculateGrundy(n / 6));
return (calculateMex(Set));
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.printf("%d", calculateGrundy(n));
}
}
// This code is contributed by PrinciRaj1992
Python3
# A recursive Python3 program to
# find Grundy Number for a game.
# Game Description : The game starts with a number- 'n'
# and the player to move divides the number- 'n' with 2, 3
# or 6 and then take the floor. If the integer becomes 0,
# it is removed. The last player to move wins.
# A Function to calculate Mex
# of all the values in that set.
def calculateMex(Set):
Mex = 0
while Mex in Set:
Mex += 1
return Mex
# A function to Compute Grundy Number of 'n'
# Only this function varies according to the game
def calculateGrundy(n):
if n == 0:
return 0
Set = set() # A Hash Table
Set.add(calculateGrundy(n // 2))
Set.add(calculateGrundy(n // 3))
Set.add(calculateGrundy(n // 6))
return (calculateMex(Set))
# Driver program to test above functions
if __name__ == "__main__":
n = 10
print(calculateGrundy(n))
# This code is contributed by Rituraj Jain
C#
/* A recursive C# program to find Grundy Number for
a game.
Game Description: 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. */
using System;
using System.Collections.Generic;
class GFG
{
// A Function to calculate Mex of
// all the values in that set.
static int calculateMex(HashSet<int> Set)
{
int Mex = 0;
while (Set.Contains(Mex))
{
Mex++;
}
return (Mex);
}
// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
static int calculateGrundy(int n)
{
if (n == 0)
{
return (0);
}
// A Hash Table
HashSet<int> Set = new HashSet<int>();
Set.Add(calculateGrundy(n / 2));
Set.Add(calculateGrundy(n / 3));
Set.Add(calculateGrundy(n / 6));
return (calculateMex(Set));
}
// Driver code
public static void Main()
{
int n = 10;
Console.WriteLine(calculateGrundy(n));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
/* A recursive Javascript program to find
Grundy Number for a game.
Game Description : 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. */
// A Function to calculate Mex of all
// the values in that set.
function calculateMex(set)
{
let Mex = 0;
while (set.has(Mex))
{
Mex++;
}
return (Mex);
}
// A function to Compute Grundy Number
// of 'n'. Only this function varies
// according to the game
function calculateGrundy(n)
{
if (n == 0)
{
return (0);
}
// A Hash Table
let set = new Set();
set.add(calculateGrundy(Math.floor(n / 2)));
set.add(calculateGrundy(Math.floor(n / 3)));
set.add(calculateGrundy(Math.floor(n / 6)));
return(calculateMex(set));
}
// Driver code
let n = 10;
document.write(calculateGrundy(n));
// This code is contributed by avanitrachhadiya2155
</script>
Output :
0
The above solution can be optimized using Dynamic Programming as there are overlapping subproblems.
References-
https://en.wikipedia.org/wiki/Mex_(mathematics)
https://en.wikipedia.org/wiki/Number
In the next post, we will be discussing solutions to Impartial Games using Grundy Numbers or Numbers.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem