Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 14, 2018 00:35
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/cec3e1ba670dd809287d3fd5410fa889 to your computer and use it in GitHub Desktop.
Save jianminchen/cec3e1ba670dd809287d3fd5410fa889 to your computer and use it in GitHub Desktop.
Root of number - binary search
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