Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 27, 2018 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/aff4ccbf1e70f1c5b07e5124f9247ba1 to your computer and use it in GitHub Desktop.
Save jianminchen/aff4ccbf1e70f1c5b07e5124f9247ba1 to your computer and use it in GitHub Desktop.
Root of number - mock interview 12:00 PM -
import java.io.*;
import java.util.*;
class Solution {
static double root(double x, int n) {
if (x == 0 || x == 1){
return x;
}
if (n == 1){
return x;
}
double lo = 0;
double hi = Math.max(1, x);
int iterations = 200;
double guess = 0;
while(iterations > 0){
iterations--;
guess = lo + (hi-lo)/2;
double guessResult = exp(guess,n);
if (guessResult <= 0 || guessResult > x){
hi = guess;
} else {
lo = guess;
}
}
return guess;
}
private static double exp(double x, int n){
if (n == 1) {
return x;
}
double result = 1;
double base = x;
while(n > 0){
if ((n&1) != 0){
result *= base;
}
base *= base;
n >>= 1;
}
return result;
}
public static void main(String[] args) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment