Skip to content

Instantly share code, notes, and snippets.

@sawant
Created August 27, 2014 16:40
Show Gist options
  • Save sawant/4080724c9030c78319aa to your computer and use it in GitHub Desktop.
Save sawant/4080724c9030c78319aa to your computer and use it in GitHub Desktop.
3.2 Recursion
/*
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 corresponding to this description. The function should accept a number parameter and return a Boolean.
Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?
*/
var isEven = function( number ) {
if( number === 0 ) // if 0
return true;
else if( number === 1 ) // if 1
return false;
else if( number < 0 ) // if negative number
return isEven( number * -1 ); // multiply by -1 to make it positive
else
return isEven( number - 2 ); // recursion
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment