Home > Web Front-end > JS Tutorial > Codewars - You&#re a square!

Codewars - You&#re a square!

Linda Hamilton
Release: 2025-01-03 03:05:39
Original
676 people have browsed it

Salutations.

Codewars - You

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.

Codewars - You

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;
}
Copy after login

This is wrong. I went with n2=2(n1)2(n2)2 2n^2 = 2(n − 1)^2 − (n − 2)^2 2n2=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;
}
Copy after login

Annnnnnnnnnnnd:
Codewars - You

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;
}
Copy after login

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

Bye bye. Drink water ???.

Previous

The above is the detailed content of Codewars - You&#re a square!. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template