The second problem of my DevAdvent 2022 concerns square roots. The story of the problem is about cubes, squares and a passion for the numbers. But long story short, it’s about whether a number is a perfect square or not.

The problem is very simple, and my solution requires only a couple of steps:

export default function isSquare(n: number): boolean {
  const square: number = n ** 0.5;
  const truncated: number = Math.trunc(square);

  return square == truncated;

In JavaScript it becomes:

const isSquare = function (n) {
  const square = n ** 0.5;
  const truncated = Math.trunc(square);

  return square == truncated;

Put into words, first I calculate the square of the number. To do this I use the exponential operator ** setting 1/2 as the exponent. Alternatively, I can use Math.sqrt().

const square = n ** 0.5;
const square = Math.sqrt(n);

Then I have to figure out if the resulting number is integer. I can do it in two ways. The long way is by truncating the number and checking that the result is equal to the original number.

const truncated = Math.trunc(square);
const isInteger square == truncated;

The easiest way is to use the Number.isInteger() method.

const isInteger = Number.isInteger(square);

Finally I can also use the Remainder % operator to check if the remainder of division by 1 returns 0.

const isSquare = (n) => Math.sqrt(n) % 1 === 0;