Salutations.
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.
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.
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; }
This is wrong. I went with
n2=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.
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; }
Annnnnnnnnnnnd:
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.
Just use Math.sqrt():
var isSquare = function(n){ let nIsSquare = false; if (n>=0) { nIsSquare = Number.isInteger(Math.sqrt(n)); } return nIsSquare; }
Not the best, but the simplest solution. Does the job.
Bye bye. Drink water ???.
Previous
The above is the detailed content of Codewars - Youre a square!. For more information, please follow other related articles on the PHP Chinese website!