## PayPal Interview Question

Software Engineer / Developers**Country:**United States

**Interview Type:**Written Test

public class Power {

public static int calPower(int a, int b){

if(a==0)

return 0;

if(b==0)

return 1;

int result =calPower(a,b/2);

if(b%2==0)

return result * result;

else

return a * result * result;

}

public static void main(String[] args) {

System.out.println("result "+calPower(10,3));

}

}

Works for both positive and negative exponent.

Memory efficient implementation. Complexity : O(log n)

```
public class Practice63 {
public static void main(String[] args){
int a = 2;
int b = 3;
System.out.println(power(a,b));
}
public static double power(int a, int b){
double temp = 1;
boolean isNeg = false;
if(b<0){
b = -b;
isNeg = true;
}
while(b>0){
if((b&1) == 1){
temp = temp * a;
}
a = a*a;
b = b>>1;
}
if(isNeg)
return 1/temp;
else
return temp;
}
}
```

to satisfy power(0,-1), change the last condition as

if(isNeg && temp > 0)

return 1/temp

This is to avoid 1/0 condition, in case for a = 0 and b = -1(negtive value)

```
decimal sayi = decimal.Parse(Console.ReadLine());
decimal us = decimal.Parse(Console.ReadLine());
decimal sonuc = 1;
for (int i = 0; i < Math.Abs(us); i++) sonuc *= sayi;
if (sayi == 0 && us < 0)
Console.WriteLine("Can't divide by 0");
else
Console.WriteLine(us > 1 ? sonuc : Convert.ToDecimal(1 / sonuc));
Console.ReadKey();
```

it works

package com.math.util;

public class ExponentClass {

public static void main(String[] args) {

ExponentClass exponentClass = new ExponentClass();

System.out.println(" Power of base " + exponentClass.power(5, 4));

}

public int power(int base, int exponent) {

int result = 1;

for (int i = 0; i < exponent; i++) {

result = result * base;

}

return result;

}

}

Assuming b is integer and for b negative we can make some minor change in code to get the result.

```
public class Indices {
public static int prod(int a, int b) {
if(a==0)
return 0;
else if (b==0)
return 1;
else
return a*prod(a, b-1);
}
public static void main(String[] args){
System.out.println(prod(a, b))
}
}
}
```

Your solution is effectively the same as

```
int result = 1;
for (int i = 1; i<b; i++) result *= a;
```

and you pay the extra cost of recursive function call and memory space for recursion.

@chriscow: you are right , thanks for suggestion abt recursive function and for output 0^0, the solution can be rectified by order of changing the condition statement :

Also i think result should be initialized with value of a rather than 1(which result in giving output a^(b-1))

statement :

```
public class Indices {
public static int prod(int a, int b) {
if(b==0)
return 1;
else if (a==0)
return 0;
int result = a;
for (int i = 1; i<b; i++) result *= a;
return result ;
}
public static void main(String[] args){
System.out.println(prod(a,b));
}
}
```

I assume b is integer.

Java code:

- chriscow January 25, 2014