Emmanuel Akinfulubi

JavaScriptMath

Check if a number is a perfect square in JavaScript

Intermediate · 4 min read

A perfect square is a whole number you get by multiplying a whole number by itself. 16 is 4 times 4, so it is a perfect square. 26 is not: no whole number times itself gives 26.

You need this check for grid layouts (can 36 photos make a square grid?), for some number puzzles, and as a quick filter in math code. In this tutorial you will write isPerfectSquare(n) in a way you can trust, and see why the obvious version, "take the square root and square it back", misses for 87 of the first 200 numbers and even calls 11 a perfect square. You need to know Math.sqrt and if statements.

Square roots are usually not exact

Math.sqrt(16) is exactly 4. But Math.sqrt(2) is an endless decimal, 1.41421356..., and a JavaScript number can only keep about 16 significant digits of it. So the value you get back is very close to the true root, but not equal to it.

JavaScript

console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(26)); // 5.0990195135927845

That tiny gap is harmless when you are drawing a circle. It matters when you compare with ===, which demands an exact match.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

47 Perfect squares, tested in integers

fair

Decide whether an integer is a perfect square without trusting a float comparison. Then find how many of the first 200 integers fail the naive Math.sqrt(n) ** 2 === n test.

Stuck? Three hints, smallest first
  1. 1. Round the root to the nearest integer, then square it back and compare exactly.
  2. 2. Math.sqrt(n) ** 2 === n compares two irrational approximations and usually loses.
  3. 3. Cheap pre-filters exist: a square never ends in 2, 3, 7 or 8.

Step 1: the obvious test, and how often it fails

The natural first idea: take the square root, square it back, and see if you get the number you started with.

Step 1

console.log(Math.sqrt(16) ** 2 === 16); // true
console.log(Math.sqrt(2) ** 2);         // 2.0000000000000004
console.log(Math.sqrt(3) ** 2);         // 2.9999999999999996

For 16 it works. For 2 and 3 the round trip misses by a hair, so the test says false, which happens to be right. Now try 11:

JavaScript

console.log(Math.sqrt(11));            // 3.3166247903554
console.log(Math.sqrt(11) ** 2 === 11); // true

Here the rounding errors cancel out, the round trip lands exactly on 11, and the test claims 11 is a perfect square. It isn't. Count how often the round trip misses below 200:

Step 1

const roundTripFails = [];
for (let n = 0; n < 200; n++) if (Math.sqrt(n) ** 2 !== n) roundTripFails.push(n);
console.log(roundTripFails.length);      // 87
console.log(roundTripFails.slice(0, 6)); // [ 2, 3, 5, 6, 7, 8 ]

87 of 200 miss, and many of the rest, like 11, land on the number by luck rather than because it is a square. Whether the round trip is exact tells you about rounding, not about squares.

Step 2: round, then multiply whole numbers

The fix is to get back to whole numbers before comparing. Round the square root to the nearest integer, multiply it by itself, and compare that with n. Multiplying two whole numbers is exact (as long as the result stays in the safe range), so the comparison is exact too.

Step 2

function isPerfectSquare(n) {
  const root = Math.round(Math.sqrt(n));
  return root * root === n;
}
console.log([16, 25, 26].map(isPerfectSquare)); // [ true, true, false ]

For 26, Math.sqrt gives 5.099..., which rounds to 5, and 5 times 5 is 25, not 26. For 25, the root rounds to 5 and 5 times 5 is 25. No decimal is ever compared.

Step 3: reject inputs that can't be squares

What about -4 or 2.5? Math.sqrt(-4) is NaN, and NaN * NaN === -4 is false, so negatives happen to fail. But it is clearer to say what you mean. A perfect square must be a whole number that is zero or more:

Step 3

function isPerfectSquare(n) {
  if (!Number.isInteger(n) || n < 0) return false;
  const root = Math.round(Math.sqrt(n));
  return root * root === n;
}
console.log([0, 1, 16, 144, 1000000].map(isPerfectSquare)); // [ true, true, true, true, true ]
console.log([2, 26, -4, 2.5].map(isPerfectSquare));         // [ false, false, false, false ]

Number.isInteger(2.5) is false, so 2.5 is rejected before any square root is taken. This is the answer's version.

Step 4: test it on every square up to a million

Step 4

let allSquaresPass = true;
for (let k = 0; k <= 1000; k++) if (!isPerfectSquare(k * k)) allSquaresPass = false;
console.log(allSquaresPass); // true

Every square from 0 times 0 to 1000 times 1000 passes.

Step 5: where the method stops working

The method relies on root * root being exact, which holds while the result is at most Number.MAX_SAFE_INTEGER, about 9 million billion. The largest square that still fits:

Step 5

const lastSafeRoot = 94906265;
console.log(lastSafeRoot * lastSafeRoot);         // 9007199136250225
console.log(isPerfectSquare(9007199136250225));  // true
console.log(Math.sqrt(2 ** 53));                 // 94906265.62425156
console.log(isPerfectSquare(2 ** 53));           // false

2 to the 53rd is just above that last square, and its root isn't whole. Past this point, the squaring itself gets rounded and the test can no longer be trusted. For bigger numbers you would need BigInt.

Step 6: a cheap filter from the last digit

Look at the last digit of every square:

Step 6

const lastDigits = [...new Set(Array.from({ length: 200 }, (_, i) => (i * i) % 10))].sort((a, b) => a - b);
console.log(lastDigits); // [ 0, 1, 4, 5, 6, 9 ]

A square never ends in 2, 3, 7 or 8. So any number ending in one of those can be rejected with no square root at all. new Set removes duplicates, and the sort puts the digits in order.

The full solution

The answer panel has isPerfectSquare, counts the round-trip failures below 200, tests every square up to a million, and prints the 2 to the 53rd case, the largest safe square and the possible last digits. It also lists the digital roots a square can have. Press Run to see the output.

The answer

function isPerfectSquare(n) {
  if (!Number.isInteger(n) || n < 0) return false;
  const root = Math.round(Math.sqrt(n));
  return root * root === n;            // integer multiply, exact comparison
}

const roundTripFails = [];
for (let n = 0; n < 200; n++) if (Math.sqrt(n) ** 2 !== n) roundTripFails.push(n);

let allSquaresPass = true;
for (let k = 0; k <= 1000; k++) if (!isPerfectSquare(k * k)) allSquaresPass = false;

const lastSafeRoot = 94906265;         // 94906265 squared is still a safe integer
const lastDigits = [...new Set(Array.from({ length: 200 }, (_, i) => (i * i) % 10))].sort((a, b) => a - b);
const digitalRoots = [...new Set(Array.from({ length: 200 }, (_, i) => (i === 0 ? 0 : 1 + ((i * i - 1) % 9))))].sort((a, b) => a - b);

console.log('16, 25, 26     :', [16, 25, 26].map(isPerfectSquare));
console.log('failures of sqrt(n) ** 2 === n below 200:', roundTripFails.length);
console.log('first few      :', roundTripFails.slice(0, 6));
console.log('2 ** 53        :', Math.sqrt(2 ** 53), '<- not a whole root');
console.log('largest safe square:', lastSafeRoot * lastSafeRoot);
console.log('last digits of squares:', lastDigits);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('0, 1, 16, 144 and a million are perfect squares', [0, 1, 16, 144, 1000000].map(isPerfectSquare), [true, true, true, true, true]);
test('2, 26, a negative and a fraction are not', [2, 26, -4, 2.5].map(isPerfectSquare), [false, false, false, false]);
test('87 of the first 200 integers fail the sqrt round trip', roundTripFails.length, 87);
test('starting with 2, whose root squared misses by a bit', [roundTripFails[0], Math.sqrt(2) ** 2], [2, 2.0000000000000004]);
test('while rounding and squaring back is exact for every square up to a million', allSquaresPass, true);
test('2 ** 53 is not a perfect square, though its root looks close', [isPerfectSquare(2 ** 53), Math.sqrt(2 ** 53)], [false, 94906265.62425156]);
test('the largest square that is still a safe integer', [lastSafeRoot * lastSafeRoot, isPerfectSquare(9007199136250225)], [9007199136250225, true]);
test('a square never ends in 2, 3, 7 or 8', lastDigits, [0, 1, 4, 5, 6, 9]);
test('and its digital root is only ever 0, 1, 4, 7 or 9', digitalRoots, [0, 1, 4, 7, 9]);

Math.sqrt(n) ** 2 === n fails for 87 of the first 200 integers, which is the number to remember: the round trip is not occasionally lossy, it is lossy more often than not. Math.round then an integer multiply avoids the problem entirely, because the comparison happens between two exact integers rather than two approximations of an irrational.

The method holds up to root * root leaving safe-integer range, which is at 94906265 squared — just under 2 ** 53. Past that the squaring itself rounds and the test can no longer be trusted; that is BigInt territory. The two digit filters are worth knowing for bulk work: they reject 40% and 55% of candidates respectively with no root at all, and both follow from arithmetic modulo 10 and modulo 9. Exercise 35 has the third characterisation — a perfect square is exactly a number with an odd count of divisors.

Common mistakes

  • Comparing Math.sqrt(n) ** 2 === n. It compares two approximations, and it calls 11 a perfect square. Round the root and multiply whole numbers instead.
  • Ignoring the safe limit. Past 94906265 squared, root * root itself gets rounded, so the test can't be trusted. Use BigInt for numbers that big.
  • Forgetting non-integers. Without the Number.isInteger check, the intent of the function is unclear for 2.5 or -4.

Try it yourself

  1. Write squareGridSize(count) that returns the side length if count photos fit a square grid, and null otherwise.
  2. Add the last-digit filter to isPerfectSquare so numbers ending in 2, 3, 7 or 8 return false straight away.
  3. List the perfect squares between 1000 and 2000.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.