Skip to content

Instantly share code, notes, and snippets.

@kylebakerio
Last active August 29, 2015 14:16
Show Gist options
  • Save kylebakerio/afef8ec47d02aba17e47 to your computer and use it in GitHub Desktop.
Save kylebakerio/afef8ec47d02aba17e47 to your computer and use it in GitHub Desktop.
function isEven(number) {
if (number === 0) return true;
else if (number === 1) return false;
else {
if (number < 0) return isEven(number + 2);
else if (number > 35663) return "number too big";
else return isEven(number - 2);
}
};
isEven(35663)
@kylebakerio
Copy link
Author

This was the prompt:


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?

// Your code here.

console.log(isEven(50));


  • I included that number because it's the maximum number allowed that I was able to use before I had a stack overflow (though I was wondering if this might vary in different operating environments?). I played with it for a while finding how large a number it could support (since I've never written a recursive function before). But anyways, it was just me screwing around and handling a case to prevent out of control recursion causing an error.
  • I generally put stuff in a bracket on the next line, but when refactoring, I (aesthetically) feel like if it fits neatly on one line, that makes it more readable (the parent conditions stand out more, making the flow more obvious). Is it not ok in certain circumstances, specifically for very simple code?
  • How would you write this to avoid having various return statements?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment