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 :
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 | <b> /** * 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 )); } } </b> |
Output :
4 raise to 2 : 16
No comments:
Post a Comment