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

Truncate A Date to First of the Month

Writing by on Friday, 2 of November , 2007 at 2:33 pm

Want to convert 1/20/2007 to 1/1/2007 in Excel?
Use the DATE excel function.

=DATE(YEAR(A1),MONTH(A1),1)

Leave a comment

Category: Excel

Rotate Text in Excel

Writing by on Sunday, 28 of October , 2007 at 8:07 pm

Example of rotated textLooking to fit a bunch of columns on a page or improve readability of text in Excel by changing the alignment/orientation of the text? Then here are some steps.

  • Select the Cell(s) you want to change alignment for
  • Right Click and select Format Cells…
  • Select the Alignment Tab
  • Change the orientation by entering a degrees or dragging the orientation scale
  • Hit OK

Leave a comment

Category: Excel

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.