How does a negative value turn positive by calling it negative in the console?

i used Math.abs but I fail and found this solution, I am following on eloquent javascript and how did negative value is turned to positive, here is the code:

function isEven(n) {
 if (n == 0) {
  return true;
 }
else if (n == 1) {
 return false;
}
else if (n < 0) {
console.log(-n);
return isEven(-n); // turn -3 to 3?
}
 else {
 return isEven(n - 2); 
 }
 }

 console.log(isEven(-3));

Upvotes: 0

Views: 134

Answers (3)

Paul S.
Paul S.

Reputation: 66324

it has to be recursion

Lets break the mold! Using -1 instead of 2. Assuming an integer;

function isEven(x) {
    if (x === 0) return 1; // ended
    return -1 * (isEven(Math.abs(x) - 1) ? 1 : -1) === 1;
}

Other fun ways to test for even that don't need 2 or mod/remaineder

function isEven(x) {
    return Math.round(Math.sin(5 * x / Math.PI)) === 0;
}

An O(log n) recursion

function isEven(x, a) {
    if (!a) a = [true, false];
    if (a.length > x) return a[x];
    return isEven(x, a.concat(a));
}

Upvotes: 1

Luaan
Luaan

Reputation: 63732

Console has nothing to do with this.

Think back to your math class. -n is a shortened expression for (-1) * n. If you multiply two negative numbers, the result is a positive number - and since you're multiplying by negative 1 (where positive 1 is identity for multiplication), the result is the same number, but positive.

Since you're checking if (n < 0) before you multiply by -1, you'll always get a positive number.

However, this is almost definitely not what you want - the code you found seems to be an example of how to use recursion to solve common problems. In real-world Javascript, you'd want something more like this:

function isEven(x) 
{
  return (Math.abs(x) % 2) === 0;
}

Upvotes: 3

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146410

Here you are a simpler test case:

> console.log( -(-3) );
3

This is not a JavaScript peculiarity, it's how maths work.

Upvotes: 4

Related Questions