Back to Freecodecamp

Challenge 45: Perfect Square

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccab.md

latest1.2 KB
Original Source

--description--

Given an integer, determine if it is a perfect square.

  • A number is a perfect square if you can multiply an integer by itself to achieve the number. For example, 9 is a perfect square because you can multiply 3 by itself to get it.

--hints--

isPerfectSquare(9) should return true.

js
assert.isTrue(isPerfectSquare(9));

isPerfectSquare(49) should return true.

js
assert.isTrue(isPerfectSquare(49));

isPerfectSquare(1) should return true.

js
assert.isTrue(isPerfectSquare(1));

isPerfectSquare(2) should return false.

js
assert.isFalse(isPerfectSquare(2));

isPerfectSquare(99) should return false.

js
assert.isFalse(isPerfectSquare(99));

isPerfectSquare(-9) should return false.

js
assert.isFalse(isPerfectSquare(-9));

isPerfectSquare(0) should return true.

js
assert.isTrue(isPerfectSquare(0));

isPerfectSquare(25281) should return true.

js
assert.isTrue(isPerfectSquare(25281));

--seed--

--seed-contents--

js
function isPerfectSquare(n) {

  return n;
}

--solutions--

js
function isPerfectSquare(n) {
  if (n < 0) return false;
  const root = Math.floor(Math.sqrt(n));
  return root * root === n;
}