Problem Solving Fundamentals · Recursion

Take turns

mutual recursion

Take turns

You want to know whether a number is even, so you ask a friend whether one less is odd. Your friend does not want to answer alone either, so they ask you whether one less again is even. Back and forth it goes, each of you handing the slightly easier question to the other, until one of you reaches zero and can answer without asking anything.

Two people taking turns is the whole picture. Neither function calls itself. Each one calls the other, and the question gets smaller every time it changes hands. The problem is not one function's to finish alone.

The base case is the number nobody has to pass on: zero. Zero is even and not odd, so whoever holds zero answers directly, and the passing stops.

Shrink the input by one on every hand-off. A lower number each time means zero is always reachable, and the chain of calls stays finite.

Then trust the other call. When isEven hands n - 1 to isOdd, it assumes that answer is already correct and passes it straight back. Two functions that call each other this way are mutually recursive.

function isEven(n) {
  if (n === 0) {
    return true;
  }

  return isOdd(n - 1);
}

function isOdd(n) {
  if (n === 0) {
    return false;
  }

  return isEven(n - 1);
}

Neither function works without the other, and together they finish in n steps.

Export isEven and isOdd from index.js. Each returns whether its number is even or odd.

Challenge

Deciding whether a number is even feels like it needs the oddness of the number below it — and that needs the evenness below that, all the way down to zero. Export isEven and isOdd from index.js, two functions that hand the question back and forth.

isEven takes a non-negative whole number and returns true when it is even, false otherwise. isOdd does the opposite. Each calls the other on n - 1, and zero is the case that answers without calling anything.

index.js
export function isEven(_n) {
  return false;
}

export function isOdd(_n) {
  return false;
}

export function render(mount) {
  const numbers = [4, 7];

  mount.innerHTML = numbers
    .map((n) => `<p>isEven(${n}) = ${isEven(n)}, isOdd(${n}) = ${isOdd(n)}</p>`)
    .join('');
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.