Square Patio Tiles

Easybinary searchAlso known as Sqrt(x)

You have a pile of identical square paving tiles left over from a job. You want to lay them as one square patio, as large as possible. A patio with side 4 needs 4 × 4 = 16 tiles. Tiles that do not fit go back in the shed.

Given the number of tiles, how long can the side of the patio be?

Your task

Write largestSide(tiles). Return the largest whole number k with k × k ≤ tiles. With 0 tiles the answer is 0.

Do not use a built-in square root or power function. Find k by searching.

largestSide(tiles: int) → int

Examples

Example 1
Input
tiles = 17
Output
4
Why

A side of 4 uses 16 tiles, and 1 is left over. A side of 5 would need 25, which you do not have. So 4.

Example 2
Input
tiles = 36
Output
6
Why

6 × 6 = 36 exactly, so every tile is used.

Constraints

  • 0 ≤ tiles ≤ 2,000,000,000
Start with brute force

Try side 1, 2, 3, … and stop at the first one whose square is more than tiles. The answer is one less.

That takes about √tiles steps. For 2,000,000,000 tiles that is 44,721 steps. Not terrible, but binary search needs about 31, and the same idea scales to problems where a linear scan is far too slow.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code