|
| 1 | +/* |
| 2 | +Write you own Power without using multiplication(*) and division(/) operators |
| 3 | +Source: http://www.geeksforgeeks.org/write-you-own-power-without-using-multiplication-and-division/ |
| 4 | +*/ |
| 5 | +package PowerWithoutUsingMultiplicationAndDivisionOperators; |
| 6 | + |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public class UsingRecursiveAddition { |
| 10 | +public static void main(String[] args) { |
| 11 | + Scanner in = new Scanner(System.in); |
| 12 | + try{ |
| 13 | + System.out.println("Enter the two number to calculate the power in the form a^b repectively"); |
| 14 | + System.out.println("Only positive numbers should be entered"); |
| 15 | + int a = in.nextInt(); |
| 16 | + int b = in.nextInt(); |
| 17 | + System.out.println("Using multiplcative recursion we get "+pow(a,b)); |
| 18 | + System.out.println("Using nested loops "+usingNestedLoops(a,b)); |
| 19 | + } |
| 20 | + finally{ |
| 21 | + in.close(); |
| 22 | + } |
| 23 | +} |
| 24 | +/* |
| 25 | +Algorithm: |
| 26 | + Method 1 - (Using Nested Loops) |
| 27 | + |
| 28 | + We can calculate power by using repeated addition. |
| 29 | + |
| 30 | + For example to calculate 5^6. |
| 31 | + 1) First 5 times add 5, we get 25. (5^2) |
| 32 | + 2) Then 5 times add 25, we get 125. (5^3) |
| 33 | + 3) Then 5 time add 125, we get 625 (5^4) |
| 34 | + 4) Then 5 times add 625, we get 3125 (5^5) |
| 35 | + 5) Then 5 times add 3125, we get 15625 (5^6) |
| 36 | + |
| 37 | + Method 2 - (Using Recursion) |
| 38 | + Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the |
| 39 | + power b. |
| 40 | +*/ |
| 41 | +private static int usingNestedLoops(int a, int b) { |
| 42 | + if(b==0) |
| 43 | + return 1; |
| 44 | + int increment = a; // initialize increment with a |
| 45 | + int result = a; // initialize result with a |
| 46 | + for(int i=1;i<b;i++){ // Hand Run this program to understand the logic |
| 47 | + for(int j=1;j<a;j++){ |
| 48 | + result+=increment; |
| 49 | + } |
| 50 | + increment = result; |
| 51 | + } |
| 52 | + return result; |
| 53 | +} |
| 54 | +/* |
| 55 | +Analysis: |
| 56 | + Time Complexity = O(a*b) |
| 57 | + Space Complexity = O(1) |
| 58 | +*/ |
| 59 | +private static int pow(int a, int b) { |
| 60 | + if(b==0) |
| 61 | + return 1; |
| 62 | + else |
| 63 | + return mutiply(a,pow(a,b-1)); // multiplication of (a * pow(a,b-1)) |
| 64 | +} |
| 65 | + |
| 66 | +private static int mutiply(int a, int b) { |
| 67 | + if(b==0) |
| 68 | + return 0; |
| 69 | + else |
| 70 | + return a+mutiply(a,b-1); |
| 71 | +} |
| 72 | +} |
| 73 | +/* |
| 74 | +Analysis: |
| 75 | + Time Complexity = O(b^2) |
| 76 | + Space Complexity = O(1) // This is not the space complexity |
| 77 | + |
| 78 | +*/ |
0 commit comments