Reputation: 395
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:
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
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
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
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