DEV Community

Cover image for Codewars - You're a square!
Nicolás Bost
Nicolás Bost

Posted on

Codewars - You're a square!

Salutations.

Forrest says hi

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

Next one in this series is "You're a Square!". See, your LEGO addiction got a little out of hand, and you're now coding as a replacement drug.

Bruce is perfectly fine

Nah, you're fine 😎. And your next task involves squares. So the problem seeks to answer "Is this number a square?". So, how do we tackle this? However we desire. As with any coding problem.

First, solve it. Then, solve it correctly. Then, solve it correctly and fast.

  1. Step 1: Make mistakes

My first hunch led me to this:

var isSquare = function(n){
  let nIsSquare = false;
  if (n>=0) {
      nIsSquare = ( n ** 2 ) == 2 * ( (n - 1) ** 2 ) - ( (n-2) ** 2 ) + 2;
  }
  return nIsSquare;
}
Enter fullscreen mode Exit fullscreen mode

This is wrong. I went with n2=2(n1)2(n2)2+2n^2 = 2(n − 1)^2 − (n − 2)^2 + 2
Thanks Wikipedia. But this is a formula to verify n^2. I need a formula to verify n.

  1. Step 2: Do it rightMAKE MORE MISTAKES

On another wikipedia article there was a neat, short way to calculate square roots: Exponential identity.

So we fix our previous code:

var isSquare = function(n){

  let nIsSquare = false;
  if (n>=0) {
     let sqrt = Math.E ** ( Math.log(n) / 2 );
     nIsSquare = Number.isInteger(sqrt);
  }

  return nIsSquare;
}
Enter fullscreen mode Exit fullscreen mode

Annnnnnnnnnnnd:
Metal Slug BOOM

Oh, come on. Why does it fail? Oh. JavaScript does weird things with floating-point numbers. So, it's not the code's fault. Right? Guess we'll never know. Even so, I love you JS. You quirky bastard.

  1. Step 3: Do it right and fast

Just use Math.sqrt():

var isSquare = function(n){
  let nIsSquare = false;
  if (n>=0) {
     nIsSquare = Number.isInteger(Math.sqrt(n));
  }
  return nIsSquare;
}
Enter fullscreen mode Exit fullscreen mode

Not the best, but the simplest solution. Does the job.

Bye bye. Drink water 💧💧💧.

Previous

Top comments (0)