Raising a number to a power in Java
Writing by shivdev on Wednesday, 23 of April , 2014 at 4:10 pm
In Java, use the Math.pow(a, b) to raise the value of ‘a’ to the power of ‘b’.
In Microsoft Excel and some other tools the Caret (^) symbol is used for this operation.
Note that in Java, the caret (^) symbol implies XOR of the two numbers.
Here’s the difference between the two.
2 raised to 4 = 2*2*2*2 = 16 (2 to the power of 4)
2 XOR 4 = 010 XOR 100 = 110 = 6 (Binary representation of 2 = 010 ; and 4 = 100)
Here’s a simple Java code snippet to try out.
public static void main(String[] args) { System.out.println("Math.pow(2, 4) = " + Math.pow(2, 4)); // returns 16 System.out.println("2 ^ 4 = " + (2 ^ 4) ); // returns 6 (010 XOR 100 = 110) }
And here’s a SQL flavor.
mysql> select power(2, 4); +-------------+ | power(2, 4) | +-------------+ | 16 | +-------------+ 1 row in set (0.00 sec)
And a Divide & Conquer algorithm in Java.
public double power(double a, long b) { // Base Cases if (a == 0) return 0; if (b == 0) return 1; // Divide & Conquer // 2*2*2*2 = (2*2) * (2*2) = ((2)*(2)) * ((2)*(2)) double p = power(a, b/2); // Handle Negative Exponents double x = (b >= 0) ? a : 1/a; // Handle Odd & Even b's // 2*2*2*2*2 = 2 * (2*2) * (2*2) = a * p * p return (b%2 != 0) ? x*p*p : p*p; }
Leave a comment
- Add this post to
- Del.icio.us -
- Digg -
- -
- Tweet -
-
-