less than 1 minute read

Given a non-negative integer n, find a number r such that r * r = n and round down to the nearest integer.

Can you implement this without using the built-in square root?

Constraints

  • 0 ≤ n < 2 ** 31

https://binarysearch.com/problems/Guess-the-Root

ExamplesPermalink

Example 1Permalink

Input

  • n = 9

Output

  • answer = 3

Explanation

3 is the square root of 9.

Example 2Permalink

Input

  • n = 26

Output

  • answer = 5

Explanation

~5.09901951359 is the square root of 26 and rounding down gives us 5.

SolutionPermalink

int solve(int n)
{
if (n <= 1)
return n;
float guess = n / 2;
long prev = 0;
while (true)
{
guess = 0.5 * (guess + n / guess);
if (floor(guess) == prev)
{
break;
}
else
{
prev = floor(guess);
}
}
long a = (prev - 1) * (prev - 1);
long b = prev * prev;
long c = (prev + 1) * (prev + 1);
if (a <= n && b > n)
return prev - 1;
else if (b <= n && c > n)
return prev;
else
return prev + 1;
}

Leave a comment