text:  and valid move is the move that will lead the current player to winning state.
  Winning state: A tuple of values from where the current player will win the game no matter what opponent does. (If G!=0)
  Losing state: A tuple of values from where the current player will loose the game no matter what opponent does. (If G=0)
  For a given pile size n, we have two states: (1) n with no zero move available, grundy number will same as standard nim game. (2) n with zero move available, we can reach above state and other states with zero move is not a valid move, as it will lead the current player into loosing state. Therefore, g(2) = mex{0} which implies that g(2)=1. If we try to build a solution bottom-up like this, it turns out that if n is even, the grundy number is n - 1 and when it is odd, the grundy is n + 1.
  Below is the implementation of above approach:
  C++
  // CPP program for the variation // in nim game #include <bits/stdc++.h> using namespace std; // Function to return final // grundy Number(G) of game int solve(int p[], int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i] & 1) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } // driver program int main() { // Game with 3 piles int n = 3; // pile with different sizes int p[3] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero cout << "Player 2 wins"; else // if G is non zero cout << "Player 1 wins"; return 0; }
  Java
  // Java program for the variation // in nim game class GFG { // Function to return final // grundy Number(G) of game static int solve(int p[], int n) { int G = 0; for (int i = 0; i < n; i++) { // if pile size is odd if (p[i]%2!=0) // We XOR pile size+1 G ^= (p[i] + 1); else // if pile size is even // We XOR pile size-1 G ^= (p[i] - 1); } return G; } //Driver code public static void main (String[] args) { // Game with 3 piles int n = 3; // pile with different sizes int p[] = { 32, 49, 58 }; // Function to return result of game int res = solve(p, n); if (res == 0) // if G is zero System.out.print("Player 2 wins"); else // if G is non zero System.out.print("Player 1 wins"); } } // This code is contributed by Anant Agarwal.
  Output:
  Player 1 wins
  Time Complexity: | 3 cuts to cut round cake into 8 equal pieces
  - Combinatorial Game Theory | Set 4 (Sprague – Grundy Theorem)
  - Game of replacing array elements
  - Passing the Assignment
  - Check if the game is valid or not
  -.