Facebook Interview Question
348 Interview Reviews |
Back to all Facebook Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineering Intern at Facebook:
Implement a power function to raise a double to an int power, including negative powers.
| Tags: | technical, recursive algorithm, math See more , See less 8 |
See more for this Facebook Software Engineering Intern Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (6)
1 of 1 people found this helpful
#include <stdio.h>
#define MAX_ARRAY_LENGTH 256
double power(double, unsigned int);
int main(int argc, char** argv) {
double a = atof(argv[1]);
int b = atoi(argv[2]);
double result = power(a, b >> 31 == 0 ? b : -b);
if ((unsigned int) b >> 31 == 1) {
result = 1 / result;
}
printf("%f\n", result);
return 0;
}
double power(double a, unsigned int b) {
switch (b) {
case 0:
return 1.0;
case 1:
return a;
default:
return (b & 1) == 0 ? power(a * a, b >> 1) : power(a * a, b >> 1) * a;
}
}
Helpful Answer?
Yes |
No
Inappropriate?
int ipow(int base, int exp){
int result = 1;
while(exp){
if(exp & 1) { result *= exp; }
exp >>= 1;
base *= base;
}
return result;
}
Helpful Answer?
Yes |
No
Inappropriate?
1 of 2 people found this helpful
{
bool npower = (exp < 0) ? true : false;
double result = 1;
exp = abs(exp); // get the absolute value
for (int i = 0; i < exp; i++)
{
if (npower)
{
result = result/n;
}
else
{
result = result*n;
}
}
return result;
}
Helpful Answer?
Yes |
No
Inappropriate?
static double Power(double d, int exp)
{
if (d == 0 || exp == 0)
{
if (exp >= 0)
{
return 1;
}
else
{
return double.PositiveInfinity;
}
}
int expAbs = Math.Abs(exp);
double res = d;
for (int i = 1; i < expAbs; i++)
{
res *= d;
}
return (exp > 0) ? (res) : (1 / res);
}
Helpful Answer?
Yes |
No
Inappropriate?
if(y == 0) return 1;
int sign = 1;
if(y < 0) sign = -1;
y = abs(y);
double d = power(x, y/2);
if(y%2 == 0) d = d*d;
else d = x*d*d;
if(sign == -1) return 1.0/d;
else return d;
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



0 of 1 people found this helpful
by Interview Candidate: