The Square Root Estimator
MediumAcc. 86.1%
+30 XP 12
Finding the Core
You need to find the largest integer $x$ such that $x^2 le target$.
The Assignment
Your function receives a parameter named target.
- If
targetis 0 or 1, print thetargetand exit. - Initialize
lowto 1 andhightotarget. - Use a
whileloop (low <= high) to search for the root:- Find the middle point (
mid = Math.floor((low + high) / 2)). - If
mid * mid === target, you found it! Printmidand exit. - If
mid * mid < target, movelow = mid + 1and storemidas the "best answer so far". - If
mid * mid > target, movehigh = mid - 1.
- Find the middle point (
- After the loop, print the best
midthat didn't exceed the target.
01EXAMPLE 1
Input
target = 8Output
2Explanation: 2^2=4, 3^2=9. Highest integer not exceeding 8 is 2.
Constraints
- Do not use Math.sqrt().
- Must use binary search or iterative approximation.
MathLoops
JavaScriptSystem handles I/O — write your function only
Loading...
3 Hidden
Input Arguments
target16
Expected Output
4
Click RUN to test your solution