Programming fundamentalsLesson 2 of 3 in the course Recursion

Recursive Fibonacci, Subtractive GCD, and Integer Powers

5 flashcards · 5 quiz questions · 5 match pairs · 5 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

This lesson explores how recursion can define and calculate Fibonacci numbers, the greatest common divisor (GCD), and integer powers. These examples show how a problem can be reduced to smaller versions of itself until a base case is reached.

0,1,1,2,3,5,8,13,21,34,…0, 1, 1, 2, 3, 5, 8, 13, 21, 34, \ldots

F(0)=0,F(1)=1,F(n)=F(n−1)+F(n−2) for n>1F(0)=0, \quad F(1)=1, \quad F(n)=F(n-1)+F(n-2) \text{ for } n>1

All flashcards

How is a Fibonacci number defined recursively?
The base cases are F(0)=0F(0)=0 and F(1)=1F(1)=1. For n>1n>1, F(n)=F(n−1)+F(n−2)F(n)=F(n-1)+F(n-2).
What is a recursion tree?
A trace of the calls made as recursion branches into smaller calls; it can reveal repeated calculations.
How does the subtractive GCD method work?
For two positive integers, subtract the smaller from the larger and repeat. When they are equal, that value is the GCD.
What base case can a recursive power function use?
Use x0=1x^0=1. For a positive exponent, calculate xyx^y as x⋅xy−1x\cdot x^{y-1} until the exponent reaches zero.
How can a recursive power function handle a negative exponent?
For nonzero xx, use x−k=1/xkx^{-k}=1/x^k: calculate the positive power recursively and return its reciprocal. Zero cannot be raised to a negative exponent.

Quiz questions

  1. What are the two base cases in the recursive definition of the Fibonacci sequence?Answer: F(0)=0F(0)=0 and F(1)=1F(1)=1
  2. What does a recursion tree show?Answer: The calls made as recursion branches into smaller calls.
  3. Why can simple recursive Fibonacci be inefficient for large inputs?Answer: It recalculates some Fibonacci values in multiple branches.
  4. In the subtractive GCD method, what is returned when two positive inputs become equal?Answer: Their common value, which is their greatest common divisor.
  5. What value does `rec_pow(2, -4)` return?Answer: 1/161/16

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons