Created
February 25, 2018 19:27
-
-
Save jianminchen/ed81d8b53c42a1dd7e0c592e06d3e25a to your computer and use it in GitHub Desktop.
Root of number - JavaScript code - 10:00 am mock interview Feb 25, 2018
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function root(x, n) { | |
// your code goes here | |
let lowerBound = 0; | |
let higherBound = x; | |
let candidate = ((higherBound + lowerBound) / 2); | |
while (Math.abs(Math.pow(candidate, n) - x) > 0.001) { | |
if (Math.pow(candidate, n) > x) { | |
higherBound = candidate; | |
} else { | |
lowerBound = candidate; | |
} | |
candidate = ((higherBound + lowerBound) / 2); | |
} | |
return parseInt(candidate * 1000 + 0.5) / 1000.0; // (int)(d * 1000)/ 1000.0 | |
} | |
/* | |
const x = 9; | |
const p = 3; | |
console.log(root(x, p)); | |
*/ | |
/* | |
input: number => integer, power | |
output: number => float | |
error < 0.001 | |
iterate starting from 2 => candidate: | |
until | |
multiply candiate by itself times power < target (X) | |
candiate = x | |
keep on repeating candiate = candiate / 2 until candidate time to the power is less than X | |
x = 9, power = 3 | |
2 * 2 * 2 = 8 | |
3 * 3 * 3 = 27 | |
between 2 and 3 | |
current step / 10 | |
2.1 2.2 2.3 | |
currentStep / 10 | |
until currentStep < 0.001 | |
Julia's hint | |
Lower bound is 2, and upper bound is 3 -> how many numbers between 2 and 3 you have to find? | |
every step 0.1, you have 10 number, 2.1, 2.2, ..., 3.0 | |
0.001 error range | |
1000 from 2 to 3, 2, 2.001, 2.002, ,,,,3.0 | |
how to expedite the search? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment