Skip to content
BytePatterns

Integer Square Root

EasySearching#binary-search#monotonic-predicate~20m

Problem

Given a non-negative whole number, return the largest whole number whose square does not exceed it. The fractional part is discarded rather than rounded, so a number that is not a perfect square gives the value just below its true root. Built-in square root functions are not allowed.

Examples

Input:  n = 8
Output: 2
Why:    2 squared is 4 and 3 squared is 9, so the answer is cut down to 2
Input:  n = 16
Output: 4
Why:    a perfect square returns its exact root
Input:  n = 0
Output: 0
Why:    edge case, zero is its own root

Hints

0 / 3

Stuck on the idea rather than the code? Binary Search covers it.