← DiffPush

Square root of number

Baseline Binary Search · In Search Space O(log x) · O(1)

Sizing a Square Server Rack Footprint

A datacenter planner receives a floor area in square units and wants the side of the largest square rack cluster that fits exactly or smaller. When the area is not a perfect square, the planner floors the side length. Search the side-length range directly rather than calling a floating-point library routine.

Input: A single long integer x, the area.

Output: floor(sqrt(x)), the largest integer whose square does not exceed x.

Constraints

Examples

Example 1

Input: {"x":5}
Output: 2
2 squared is 4, which fits, while 3 squared overshoots 5 - so the floored side is 2.

Example 2

Input: {"x":4}
Output: 2
The area is a perfect square and the side is exactly 2.

Solve this in your browser →

Also on LeetCode ↗