Skip to content

Commit 31de2db

Browse files
Add fast exponentiation algorithm (#5715)
1 parent f8397bf commit 31de2db

File tree

2 files changed

+134
-0
lines changed

2 files changed

+134
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* This class provides a method to perform fast exponentiation (exponentiation by squaring),
5+
* which calculates (base^exp) % mod efficiently.
6+
*
7+
* <p>The algorithm works by repeatedly squaring the base and reducing the exponent
8+
* by half at each step. It exploits the fact that:
9+
* <ul>
10+
* <li>If exp is even, (base^exp) = (base^(exp/2))^2</li>
11+
* <li>If exp is odd, (base^exp) = base * (base^(exp-1))</li>
12+
* </ul>
13+
* The result is computed modulo `mod` at each step to avoid overflow and keep the result within bounds.
14+
* </p>
15+
*
16+
* <p><strong>Time complexity:</strong> O(log(exp)) — much faster than naive exponentiation (O(exp)).</p>
17+
*
18+
* For more information, please visit {@link https://en.wikipedia.org/wiki/Exponentiation_by_squaring}
19+
*/
20+
public final class FastExponentiation {
21+
22+
/**
23+
* Private constructor to hide the implicit public one.
24+
*/
25+
private FastExponentiation() {
26+
}
27+
28+
/**
29+
* Performs fast exponentiation to calculate (base^exp) % mod using the method
30+
* of exponentiation by squaring.
31+
*
32+
* <p>This method efficiently computes the result by squaring the base and halving
33+
* the exponent at each step. It multiplies the base to the result when the exponent is odd.
34+
*
35+
* @param base the base number to be raised to the power of exp
36+
* @param exp the exponent to which the base is raised
37+
* @param mod the modulus to ensure the result does not overflow
38+
* @return (base^exp) % mod
39+
* @throws IllegalArgumentException if the modulus is less than or equal to 0
40+
* @throws ArithmeticException if the exponent is negative (not supported in this implementation)
41+
*/
42+
public static long fastExponentiation(long base, long exp, long mod) {
43+
if (mod <= 0) {
44+
throw new IllegalArgumentException("Modulus must be positive.");
45+
}
46+
47+
if (exp < 0) {
48+
throw new ArithmeticException("Negative exponent is not supported.");
49+
}
50+
51+
long result = 1;
52+
base = base % mod; // Take the modulus of the base to handle large base values
53+
54+
// Fast exponentiation by squaring algorithm
55+
while (exp > 0) {
56+
// If exp is odd, multiply the base to the result
57+
if ((exp & 1) == 1) { // exp & 1 checks if exp is odd
58+
result = result * base % mod;
59+
}
60+
// Square the base and halve the exponent
61+
base = base * base % mod; // base^2 % mod to avoid overflow
62+
exp >>= 1; // Right shift exp to divide it by 2
63+
}
64+
65+
return result;
66+
}
67+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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

Comments
 (0)