Created
January 14, 2018 00:35
-
-
Save jianminchen/cec3e1ba670dd809287d3fd5410fa889 to your computer and use it in GitHub Desktop.
Root of number - binary search
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) | |
{ | |
// your code goes here | |
double lower = 0; | |
double upper = Math.Max(x, 1); | |
while (lower <= upper) | |
{ | |
double mid = (lower + upper)/2; | |
double curGuess = Math.Pow(mid, n); | |
if (Math.Abs(curGuess - x) < 0.001) | |
{ | |
return Math.Round(mid * 1000)/((double)1000); // round up math.round 0.5 -> 1, 0.4 -> 0 , mid * 1000 | |
} | |
if (curGuess > x) | |
{ | |
upper = mid; | |
} | |
else if (curGuess < x) | |
{ | |
lower = mid; | |
} | |
} | |
return -1; | |
} | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(Root(0.04, 2)); | |
} | |
} | |
/* | |
x > 1, | |
x >= x | |
x * x >= x | |
x * x * x >= x | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment