Square Patio Tiles

Easybinary searchAlso known as Sqrt(x)

You want to lay a pile of identical square tiles as one square patio, as large as possible. A side of 4 needs 4 × 4 = 16 tiles. Any tiles that do not fit in the square go back in the shed.

Given the number of tiles, you need to find the longest side the patio can have.

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 the answer is 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 sides 1, 2, 3, … until the square exceeds tiles. The answer is one less.

That is about √tiles steps: 44,721 for 2,000,000,000 tiles. Binary search needs about 31.

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