## Amazon Interview Question for Software Engineer / Developers

Country: India
Interview Type: Phone Interview

Comment hidden because of low score. Click to expand.
4
of 4 vote

O(nLogn)

``````float power(float x, unsigned int n) {
float aux = 1.0;
while (n > 0) {
if (n & 1) {    \\ odd?
aux *= x;
if (n == 1) return aux;
}
x *= x;
n /= 2;
}
return aux;
}``````

Comment hidden because of low score. Click to expand.
0

hey can u please show how is it O(nlogn) , i mean isn't it O(logn)

Comment hidden because of low score. Click to expand.
0

Yeah...The series converge from n/2, n/4, n/8....1, the time complexity will be O(lgn)...

Comment hidden because of low score. Click to expand.
0
of 0 vote

Ya it can be done in logn time. Here is the code

public double power(double d,int i)
{
if(d%2==0)
{
return power(d*d,i/2);
}
else
{
return d*power(d*d,i/2);
}
}

Comment hidden because of low score. Click to expand.
0

did your test you code? it does not work

Comment hidden because of low score. Click to expand.
1
of 1 vote

Below is the correct above code misses termination condition.

``````int power(int a, int n)
{
if (n == 1)
return a;

if (n%2 == 0)
return power(a*a,n/2);
else
return a*power(a*a,n/2);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

while(n) {
if(n&1) {
val *= x;
}
x *= x;
n = n>>1;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

///public static int pow(int a, int b) {
if (b == 1) {
return a;
}
if (b % 2 == 1) {
return a * pow(a, b / 2) * pow(a, b / 2);
}else
return pow(a, b / 2) * pow(a, b / 2);

}\\\

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public class Power {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println("the value 10^9 is " + power(10,9));

}
public static long power(long base, long power){

if(power==1)
return base;

if(power%2 == 0){
return (power(base,power/2)*power(base,power/2));

}
else{
return (power(base,power/2)*power(base,power/2)*base);

}

}

}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.