Matt
Matt

Reputation: 395

JavaScript: Too much recursion?

I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.

If I understood correctly, the author specifically wanted the following to be implemented:

  1. If a number == 0, then it is even.
  2. If a number == 1, then it is odd.
  3. "For any number N, its evenness is the same as N-2".

But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?

// Your code here.
function isEven(n){
  if(n==0){
    return true;
  }
  else if(n==1){
    return false;
  }
  else{ 
    n = n-2; 
    isEven(n);  
  }  
}

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??

Upvotes: 1

Views: 6191

Answers (3)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

To handle it recursion with that function, the value needs to be its absolute value.

console.log("isEven");

function isEven(n) {
  //Ensure that we look at the numbers absolute value
  n = Math.abs(n);
  //Do a loop instead of recursion
  if (n == 0) {
    return true;
  } else if (n == 1) {
    return false;
  } else {
    n = n - 2;
    return isEven(n);
  }
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
console.log("fasterIsEven");
//A faster way that eliminates recursion
function fasterIsEven(n) {
  return n % 2 === 0;
}
console.log(fasterIsEven(50));
console.log(fasterIsEven(75));
console.log(fasterIsEven(-1));

Javascript has a build-in method to test if something is dividable with something else, called modulus (%). This method is faster, but not recursive.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You could add another check, before decrementing/incrementing a value.

function isEven(n) {
    if (n == 0) {
        return true;
    }
    if (n == 1) {
        return false;
    }
    if (n > 0) {
        n = n - 2;
    } else {
        n = n + 2;
    }
    return isEven(n);
}

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));

Upvotes: 3

yankai
yankai

Reputation: 1

function IsEven(n){ return n%2 === 0 }

The core code is this one return n%2 === 0

In order to increase the program's strength, it is recommended to increase non-number decisions.

Upvotes: -1

Related Questions