From e93192d274cfa782156f40c23a8cf605ac93a626 Mon Sep 17 00:00:00 2001 From: roshankumar447 Date: Sat, 7 Nov 2026 20:48:59 +0530 Subject: [PATCH] feat: add nim-game algorithm with tests --- .../java/com/thealgorithms/maths/NimGame.java | 23 ++++++++++++++++++ .../com/thealgorithms/maths/NimGameTest.java | 24 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/main/java/com/thealgorithms/maths/NimGame.java create mode 100644 src/test/java/com/thealgorithms/maths/NimGameTest.java diff --git a/src/main/java/com/thealgorithms/maths/NimGame.java b/src/main/java/com/thealgorithms/maths/NimGame.java new file mode 100644 index 000000000000..f9df6a37c69b --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/NimGame.java @@ -0,0 +1,23 @@ +package com.thealgorithms.maths; + +/** + * Nim Game: Two players take turns removing 1 to 3 stones from a pile. + * The player who removes the last stone wins. Returns true if the first + * player can guarantee a win given n stones. + * + *

Key insight: if n is a multiple of 4, the second player always wins + * because whatever the first player takes (1-3), the second player can + * always take enough to leave another multiple of 4. + * + *

Time complexity: O(1), Space complexity: O(1) + * + * @see LeetCode #292 + */ +public final class NimGame { + private NimGame() { + } + + public static boolean canWinNim(int n) { + return n % 4 != 0; + } +} diff --git a/src/test/java/com/thealgorithms/maths/NimGameTest.java b/src/test/java/com/thealgorithms/maths/NimGameTest.java new file mode 100644 index 000000000000..58e342df176f --- /dev/null +++ b/src/test/java/com/thealgorithms/maths/NimGameTest.java @@ -0,0 +1,24 @@ +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class NimGameTest { + + @Test + public void testFirstPlayerWins() { + assertTrue(NimGame.canWinNim(1)); + assertTrue(NimGame.canWinNim(2)); + assertTrue(NimGame.canWinNim(3)); + assertTrue(NimGame.canWinNim(5)); + } + + @Test + public void testSecondPlayerWins() { + assertFalse(NimGame.canWinNim(4)); + assertFalse(NimGame.canWinNim(8)); + assertFalse(NimGame.canWinNim(12)); + } +}