Drills

Drills — where recursion truly reads better

Three drills — and only three, on purpose. Recursion is a taste, and most "recursion exercises" are really loops in disguise (sumTo, counting, running totals — a loop does them better, as the homework shows). So here are three problems where the recursive version genuinely reads better than the loop — because the problem's own definition is recursive. Write each, run it, compare.

1 (easy) — gcd. The greatest common divisor, by Euclid's method: the GCD of a and b is the GCD of b and a % b, until b hits 0.

gcd(48, 36) → 12      gcd(17, 5) → 1
func gcd(a, b int) int {
    if b == 0 {
        return a
    }
    return gcd(b, a%b)
}

Notice the code is the mathematical definition, line for line — no loop variable, no running state. That's the sign recursion actually fits.

2 (medium) — isPalindrome. A word reads the same forwards and backwards. Its definition is already recursive: the ends match, and the middle is itself a palindrome.

isPalindrome("oro") → true      isPalindrome("labas") → false
func isPalindrome(s string) bool {
    r := []rune(s)
    if len(r) <= 1 {
        return true // 0 or 1 character: nothing to contradict it
    }
    if r[0] != r[len(r)-1] {
        return false
    }
    return isPalindrome(string(r[1 : len(r)-1]))
}

The []rune is doing real work — remember lesson 7. Compare characters, not bytes, or a Lithuanian palindrome like "ąžžą" would break where a two-byte letter meets a byte index.

3 (harder) — toBinary. Turn a number into its binary text. The recursive shape falls out of the definition: the binary of n is the binary of n/2 followed by the last bit n%2.

toBinary(13) → "1101"      toBinary(10) → "1010"
func toBinary(n int) string {
    if n == 0 {
        return "0"
    }
    if n == 1 {
        return "1"
    }
    return toBinary(n/2) + fmt.Sprint(n%2)
}

Here recursion is genuinely clearer than a loop: the digits come out most-significant-first, in order, for free. The loop version has to build the string backwards and reverse it — more code, more chances to slip.

Tip. That's the whole taste. Notice what these three share: a definition that refers to a smaller version of itself — Euclid's step, the palindrome's middle, the halved number. When you don't see that self-similar shape (and your flat book list doesn't have it), reach for a loop. Recursion returns, properly, in the Algorithms course.