Skip to content
Algorithms for Beginners

Problems / Binary search

Whole square root

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

Given a whole number n, return the biggest whole number r whose square, r × r, is not more than n.

For perfect squares that's the exact square root: for n = 49, it's 7. Otherwise it's the square root rounded down: for n = 50, 7 × 7 = 49 fits but 8 × 8 = 64 is too much, so it's 7 again.

Examples

  1. Example 1

    Input
    n = 49
    Output
    7

    7 × 7 = 49 exactly.

  2. Example 2

    Input
    n = 50
    Output
    7

    7 × 7 = 49 fits; 8 × 8 = 64 is too much.

  3. Example 3

    Input
    n = 0
    Output
    0

Rules

  • n is between 0 and 2,000,000,000,000 (two trillion).
  • Don't use Math.sqrt, Math.pow or **: the point is to find it yourself.

Your solution

JavaScript · Press Esc then Tab to leave the editor

function wholeSquareRoot(n) {
  // Return the biggest r with r * r <= n.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in binary search