Lesson 9 of 24

Recursion

10 min 30 XP

In recursion a function calls itself on a smaller input until a base case stops it. The Tower of Hanoi is the classic example: n disks need 2ⁿ - 1 moves.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Challenge

+30 XP

Write a recursive long long fastPower(long long base, int exp): when exp is even compute half = fastPower(base, exp / 2) and return half * half. In main(), read base and exp and print the result. Input: 2 40 → Output: 1099511627776

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.