Friday, 6 December 2013

Find Power of a number in Java?

There are two ways to find power of a number. One is iterative which is very simple(Just multiply the number power number of times) and other is recursive. Following is the code to get power of a number in recursive way.



Code : 


/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 6/12/13
 * Time: 3:08 PM
 * To change this template use File | Settings | File Templates.
 */
public class PowerCalculator {

    public static int pow(int base, int power){

        if(power == 1){
            return base;
        }
        if(power % 2 == 0){
            return pow(base, power/2) * pow(base, power/2);
        }
        else {
            return pow(base, power/2) * pow(base, power/2) + base;
        }
    }

    public static void main(String args []){

        System.out.println("4 raise to 2 : " + PowerCalculator.pow(4,2));

    }

}

Output :

4 raise to 2 : 16

No comments:

Post a Comment

t> UA-39527780-1 back to top