-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFastExponentiation.java
40 lines (28 loc) · 1.07 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
36
37
38
39
import java.util.Scanner;
public class FastExponentiation {
public static double fastPower(double base, int exponent) {
if (exponent == 0) {
return 1.0;
}
else if (exponent % 2 == 0) {
// If the exponent is even, use the formula (a^b)^2 = a^(2b)
double halfPower = fastPower(base, exponent / 2);
return halfPower * halfPower;
}
else {
// If the exponent is odd, use the formula a^(2b+1) = a^(b) * a^(b) * a
double halfPower = fastPower(base, exponent / 2);
return halfPower * halfPower * base;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base value");
double base = sc.nextDouble();
System.out.println("Enter the base exponent");
int exponent = sc.nextInt();
double result = fastPower(base, exponent);
System.out.println(base + " ^ " + exponent + " = " + result);
sc.close();
}
}