samuelmarina / is-even

Is a number even?
1.85k stars 193 forks source link

Detect even digits using the power of MATHS! #175

Closed ghost closed 3 years ago

ghost commented 3 years ago

Instead of making if statments for every number (words not included), we can use the Modulo operation to check if the digit if even or not.

We can do this by doing n % 2. It seems to break after 899 999 999 999 999 though (After it, it just gives 0).

To add this we can do something like:

if (foo >= 900000000000) {
  // When it's over/equal to the limit
} else if (foo % 2 === 0) {
  // When its even
} else if (foo % 2 === 1) {
  // When its odd
} else if // ...

Example:

# 0 = even
# 1 = odd

> 1%2
1
> 2%2
0
> 4%2
0
> 8%2
0

My hypothesis is that it would make the file size smaller, thus making node_modules smaller, and making my internet not dying.

Jagath918 commented 3 years ago

F modulo, this too ez

northmatt commented 3 years ago

My question is why use modulo over bitwise? In JS its somewhat better perf wise and other languages is way better perf wise (thankyou JS for not having INTs). Here is part of a function mentioned in #124 to support string values, but also fixed in removing the else statement (you generally dont want them due to how CPUs try to optimize if statements) and using bitwise.

function IsEven(n) {
  if (isNaN(+n)) {
    return !!n.match(/(?:zero|two|four|six|eight|ten|twelve|fourteen|sixteen|eighteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion)$/gi);
  }

  return !(+n & 1);
}
Jagath918 commented 3 years ago

I can understand that using a modulo is more efficient but our Samuel Miller dosen't want it that way. I hope you catch the drift and if you are still unable to understand plz watch this vid: https://www.youtube.com/watch?v=Re3rijPsGoY&t=3s I hope this vid helps. 😎

ghost commented 3 years ago

My question is why use modulo over bitwise?

@northmatt :p it's the first thing that came to my mind

ghost commented 3 years ago

I can understand that using a modulo is more efficient but our Samuel Miller dosen't want it that way. I hope you catch the drift and if you are still unable to understand plz watch this vid: https://www.youtube.com/watch?v=Re3rijPsGoY&t=3s I hope this vid helps. sunglasses

Ah i didn't know there was any PR that did this