Can someone please take a look at these recursive functions, offer some advice on the code, or just critique my attempt into thinking recursively?
Problem:
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 a Boolean. - eloquentJavascript, chapter 3
My attempt:
function isEven(x) {
if (x < 0 ) {
return false
}
else if (x % 2 == 0) {
return true
} else {
return isEven(x-2)
}
}
Offical Solution:
function isEven(n) { if (n == 0) return true; else if (n == 1) return false; else if (n < 0) return isEven(-n); else return isEven(n - 2); }
I know there are many ways to write the same piece of functionality but I want to know if the following code holds up to scrutiny. The official solution I checked my code against is obviously different but I'm getting the correct solutions.
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
What events does
else if (n < 0)
return isEven(-n);
handle that,
else
return isEven(n - 2);
doesn't?
I started reading 'the little Schemer' on the advice of Douglas Crockford in an attempt to learn how to think recursively but the examples are in Scheme
which just looks like ((( n ) * atom)) to me...so not very useful until I can read the syntax.
-2
input to both functions. And using%
and recursion is against the spirit of the problem as recursion was to avoid the complex%
operation. \$\endgroup\$