Mutual recursion (even / odd)
Medium TimeO(n) SpaceO(n)
Given a number n, zero or greater, decide whether it is even. Neither function may use modulo or division, and the answer has to come from two functions that call each other. 0 is even, and is not odd.
Examples
Example 1
- Input
- n = 6
- Output
true6 = 2 × 3, so the answer istrue.
Example 2
- Input
- n = 7
- Output
- 7 leaves one over when paired off, so the answer is
falsefalse.
The Code
function isEven(n) {
if (n === 0) return true;
return isOdd(n - 1);
}
function isOdd(n) {
if (n === 0) return false;
return isEven(n - 1);
}
isEven(6);Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Power Raise a number to a power one multiply at a time.
- Sum of digits Peel one digit off at a time with the modulo trick.