I was asked a question at my Apple interview.
Write a function to find the square root using only +-*/.
Lets see who can do that and whos is the fastest.
Please provide a benchmark result in your reply.
without using conditionals?
Yea that works.
heres is my implementation
Please dont look at it if you have not done yours yet.
http://pastie.textmate.org/192519
and benchmarks, 100 run throughs
http://pastie.textmate.org/192524
This might not strictly meet the requirements since I did make use of the abs() function, I'll let you guys decide. #include #include int main(int argc, char *argv[]) { float argument = atof(argv[1]); float guess = argument; float oldguess = 0.0; float tolerance = .0000000001; int cnt = 0; float temp = guess - oldguess; while (abs(temp) > tolerance) { oldguess = guess; guess = ( oldguess + ( argument / oldguess ) ) / 2.0; cnt++; temp = guess - oldguess; }
#include #include int main(int argc, char *argv[]) { float argument = atof(argv[1]); float guess = argument; float oldguess = 0.0; float tolerance = .0000000001; int cnt = 0; float temp = guess - oldguess; while (abs(temp) > tolerance) { oldguess = guess; guess = ( oldguess + ( argument / oldguess ) ) / 2.0; cnt++; temp = guess - oldguess; }
std::cout << "Square root of " << argument << " is approximately " << guess << std::endl; std::cout << "Derived in " << cnt << " iterations." << std::endl; }
without using conditionals?
without using conditionals?
Yea that works.
Yea that works.
heres is my implementation
Please dont look at it if you have not done yours yet.
http://pastie.textmate.org/192519
and benchmarks, 100 run throughs
http://pastie.textmate.org/192524
This might not strictly meet
This might not strictly meet the requirements since I did make use of the abs() function, I'll let you guys decide.
#include
#include
int main(int argc, char *argv[])
{
float argument = atof(argv[1]);
float guess = argument;
float oldguess = 0.0;
float tolerance = .0000000001;
int cnt = 0;
float temp = guess - oldguess;
while (abs(temp) > tolerance)
{
oldguess = guess;
guess = ( oldguess + ( argument / oldguess ) ) / 2.0;
cnt++;
temp = guess - oldguess;
}
std::cout << "Square root of " << argument << " is approximately " << guess << std::endl;
std::cout << "Derived in " << cnt << " iterations." << std::endl;
}
Navigation
Popular content
Active forum topics