Created
December 28, 2017 06:27
-
-
Save jianminchen/8571ac042d579b96f7fca4124d34fc3f to your computer and use it in GitHub Desktop.
Root of number - mock interview 30 minutes
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
using System; | |
class Solution | |
{ | |
public static double Root(double x, int n) // x = 7, n = 3 | |
{ | |
if(x < 0) // false | |
{ | |
return -1; | |
} | |
if(x < 1) // false | |
{ | |
return binarySearch(x, n, x, 1); | |
} | |
else | |
{ | |
return binarySearch(x, n, 1, x); // 1, 7 | |
} | |
} | |
private static double binarySearch(double x, int n, double start, double end) | |
{ | |
const double range = 0.001; | |
while (start <= end) // 1, 7, 1 - 4.5 | |
{ | |
var middle = start + (end - start)/ 2; // 1 + 6.0/2 = 4.5 , 1 + 3.5/2 = 2.75 | |
var middleValue = Math.Pow(middle, n); // 4.5^3 | |
// base case | |
if(Math.Abs(middleValue - x) < range) // 7 - 4.5^3 false | |
{ | |
return middle; | |
} | |
else if( middleValue < x) | |
{ | |
start = middle; | |
} | |
else | |
{ | |
end = middle; // 4.5 | |
} | |
} | |
return -1; | |
} | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(Root(1, 3)); | |
} | |
} | |
// guess and check | |
// x = 7, 0 - 7 , n = 3, 1 - 7 | |
// binary search 1 + (7 -1)/ 2 = 4.5 ^3 vs 7, get rid of half range -> left side | |
// error range < 0.001 -> 1.913 | |
// 0< x < 1, [x, 1) | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment