-
Notifications
You must be signed in to change notification settings - Fork 0
/
FastExponentiation.java
35 lines (30 loc) · 1.43 KB
/
FastExponentiation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fast Exponentiation (Exponentiation by Squaring): This algorithm computes large exponentiations efficiently.
// Bitwise operations help optimize the process by breaking down the exponentiation into smaller steps.
public class FastExponentiation {
// This function calculates base^exponent using the Fast Exponentiation algorithm.
public static long fastExponentiation(long base, long exponent) {
// Base case: If the exponent is 0, return 1.
if (exponent == 0) {
return 1;
}
// If the exponent is even, reduce the problem by half and square the result.
if (exponent % 2 == 0) {
long halfResult = fastExponentiation(base, exponent / 2);
return halfResult * halfResult;
}
// If the exponent is odd, reduce the problem by half and square the result,
// then multiply by the base.
else {
long halfResult = fastExponentiation(base, (exponent - 1) / 2);
return base * halfResult * halfResult;
}
}
public static void main(String[] args) {
long base = 2; // Base number
long exponent = 10; // Exponent
// Calculate base^exponent using fast exponentiation
long result = fastExponentiation(base, exponent);
// Display the result
System.out.println(base + "^" + exponent + " = " + result);
}
}