Square root by hand
- O(n) · Medium
- Full plan
- Python
- JavaScript
- loops
- operations
- search
Problem
Write a function that takes a whole number greater than 0 and returns its square root: the number that multiplied by itself gives that number. The root of 25 is 5, because 5 times 5 is 25.
The number you get is always a perfect square, so the root is always a whole number. You do not have to think about what happens with 10.
You cannot use the square root the language already brings (math.sqrt, Math.sqrt, ** 0.5): the whole point is to look for it yourself.
Idea: try candidates with a while. Start at 1 and go up one by one while the candidate times itself still falls short. The first one that reaches is the answer.
Examples
Four
4 → 2
The example
25 → 5
Three digits
196 → 14
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def square_root(n):
passJavaScript
function squareRoot(n) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.