Skip to content

Instantly share code, notes, and snippets.

@mojenmojen
Created September 25, 2016 16:59
Show Gist options
  • Save mojenmojen/109ce7b77a3a04ef9a98df3715988cb4 to your computer and use it in GitHub Desktop.
Save mojenmojen/109ce7b77a3a04ef9a98df3715988cb4 to your computer and use it in GitHub Desktop.
We’ve seen that % (the remainder operator) can be used to test whether a number is even or odd by using % 2 to check whether it’s divisible by two. Here’s another way to define whether a positive whole number is even or odd: Zero is even. One is odd. For any other number N, its evenness is the same as N - 2. Define a recursive function isEven co…
// Recursive function to determine if a number is even
function isEven( checkNum ) {
// if the number is negative then convert it to positive
if ( checkNum < 0 )
checkNum *= -1;
// if the number is zero then it's even
if ( checkNum == 0 ) {
result = true;
}
// if the number is odd then it's odd
else if ( checkNum == 1 ) {
result = false;
}
// if the number isn't 0 or 1 then keep subtracting until it is
else {
checkNum = checkNum - 2;
isEven( checkNum );
}
return result;
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment