Raising a number to a power in Java

Writing by 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

Category: Excel,Java,SQL DB

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.