Last active
April 28, 2021 03:01
-
-
Save jonurry/95ce2b5e98a2c9cfb44b13da37aa2105 to your computer and use it in GitHub Desktop.
3.2 Recursion (Eloquent JavaScript Solutions)
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
function isEven(num) { | |
if (num == 0) | |
return true; | |
if (num == 1) | |
return false; | |
if (num < 0) | |
return "??"; | |
else return isEven(num - 2); | |
} | |
console.log(isEven(50)); | |
// → true | |
console.log(isEven(75)); | |
// → false | |
console.log(isEven(-1)); | |
// → ?? |
Hints
Your function will likely look somewhat similar to the inner find
function in the recursive findSolution
example in this chapter, with an if/else
if/else
chain that tests which of the three cases applies. The final else
, corresponding to the third case, makes the recursive call. Each of the branches should contain a return
statement or in some other way arrange for a specific value to be returned.
When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort.
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 see 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 single parameter (a positive, whole number) and return aBoolean
.Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?