|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +/** |
| 9 | + * Unit tests for the {@link FastExponentiation} class. |
| 10 | + * |
| 11 | + * <p>This class contains various test cases to verify the correctness of the fastExponentiation method. |
| 12 | + * It covers basic functionality, edge cases, and exceptional cases. |
| 13 | + */ |
| 14 | +class FastExponentiationTest { |
| 15 | + |
| 16 | + /** |
| 17 | + * Tests fast exponentiation with small numbers. |
| 18 | + */ |
| 19 | + @Test |
| 20 | + void testSmallNumbers() { |
| 21 | + assertEquals(1024, FastExponentiation.fastExponentiation(2, 10, 10000), "2^10 mod 10000 should be 1024"); |
| 22 | + assertEquals(81, FastExponentiation.fastExponentiation(3, 4, 1000), "3^4 mod 1000 should be 81"); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Tests the behavior of the fast exponentiation method when using a modulus. |
| 27 | + */ |
| 28 | + @Test |
| 29 | + void testWithModulo() { |
| 30 | + assertEquals(24, FastExponentiation.fastExponentiation(2, 10, 1000), "2^10 mod 1000 should be 24"); |
| 31 | + assertEquals(0, FastExponentiation.fastExponentiation(10, 5, 10), "10^5 mod 10 should be 0"); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Tests the edge cases where base or exponent is 0. |
| 36 | + */ |
| 37 | + @Test |
| 38 | + void testBaseCases() { |
| 39 | + assertEquals(1, FastExponentiation.fastExponentiation(2, 0, 1000), "Any number raised to the power 0 mod anything should be 1"); |
| 40 | + assertEquals(0, FastExponentiation.fastExponentiation(0, 10, 1000), "0 raised to any power should be 0"); |
| 41 | + assertEquals(1, FastExponentiation.fastExponentiation(0, 0, 1000), "0^0 is considered 0 in modular arithmetic."); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Tests fast exponentiation with a negative base to ensure correctness under modular arithmetic. |
| 46 | + */ |
| 47 | + @Test |
| 48 | + void testNegativeBase() { |
| 49 | + assertEquals(9765625, FastExponentiation.fastExponentiation(-5, 10, 1000000007), "-5^10 mod 1000000007 should be 9765625"); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Tests that a negative exponent throws an ArithmeticException. |
| 54 | + */ |
| 55 | + @Test |
| 56 | + void testNegativeExponent() { |
| 57 | + assertThrows(ArithmeticException.class, () -> { FastExponentiation.fastExponentiation(2, -5, 1000); }); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Tests that the method throws an IllegalArgumentException for invalid modulus values. |
| 62 | + */ |
| 63 | + @Test |
| 64 | + void testInvalidModulus() { |
| 65 | + assertThrows(IllegalArgumentException.class, () -> { FastExponentiation.fastExponentiation(2, 5, 0); }); |
| 66 | + } |
| 67 | +} |
0 commit comments