Created
April 1, 2015 09:55
-
-
Save ddeveloperr/80354e82e6f4050fd298 to your computer and use it in GitHub Desktop.
Define a recursive function isEven in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Define a recursive function isEven corresponding to this description. | |
The function should accept a number parameter and return a Boolean. | |
Test it on 5 and 68. See how it behaves on -1...-22... */ | |
var isEven = function(num) { | |
num = Math.abs(num); // convert to absolute value to account to negative numbers | |
// Why I used Math.abs() see here: http://devdocs.io/javascript/global_objects/math/abs | |
if (num === 0) | |
return true; | |
else if (num === 1) | |
return false; | |
else | |
return isEven(num -2); | |
} | |
console.log(isEven(5)); | |
// → false | |
console.log(isEven(68)); | |
// → true | |
console.log(isEven(-1)); | |
// → false | |
console.log(isEven(-22)); | |
// → true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment