Even/Odd Check via Mutual Recursion

Medium ⏱ 12 min 61% acceptance ★★★★☆ 4.2
Implement two functions, is_even(n) and is_odd(n), that call each other recursively (mutual recursion) to determine the parity of a non-negative integer n, without ever using n % 2.

Examples

Example 1
Input
is_even(4)
Output
True
Explanation

is_even(4) -> is_odd(3) -> is_even(2) -> is_odd(1) -> is_even(0) -> True.

Example 2
Input
is_odd(7)
Output
True
Explanation

7 unwinds down to the base cases and resolves to True.

Constraints

  • n >= 0
  • Do not use the % operator.

Topics

RecursionFunctions

Companies

IBMCapgemini

Hints

Hint 1

Base cases: is_even(0) is True, is_odd(0) is False.

Hint 2

is_even(n) delegates to is_odd(n - 1); is_odd(n) delegates to is_even(n - 1).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.