Skip to content

Add simple recursion examples: factorial, fibonacci, sum_of_digits #12834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions other/simple_recursion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""
Simple Recursion Examples.

This module contains a few basic examples of recursion for beginners.

Functions:
- factorial(n): Calculate factorial of n.
- fibonacci(n): Calculate nth Fibonacci number.
- sum_of_digits(n): Calculate sum of digits of n.

Each function has doctests to verify correct behavior.
"""


def factorial(n: int) -> int:
"""
Calculate the factorial of a non-negative integer n using recursion.

Args:
n (int): Non-negative integer.

Returns:
int: Factorial of n.

Raises:
ValueError: If n is negative.

Examples:
>>> factorial(5)
120
>>> factorial(0)
1
>>> factorial(1)
1
"""
if n < 0:
raise ValueError("Input must be a non-negative integer")
if n == 0:
return 1
return n * factorial(n - 1)


def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using recursion.

Args:
n (int): Non-negative integer index.

Returns:
int: nth Fibonacci number.

Raises:
ValueError: If n is negative.

Examples:
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(7)
13
"""
if n < 0:
raise ValueError("Input must be a non-negative integer")
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)


def sum_of_digits(n: int) -> int:
"""
Calculate the sum of digits of a non-negative integer n using recursion.

Args:
n (int): Non-negative integer.

Returns:
int: Sum of digits of n.

Raises:
ValueError: If n is negative.

Examples:
>>> sum_of_digits(123)
6
>>> sum_of_digits(0)
0
>>> sum_of_digits(999)
27
"""
if n < 0:
raise ValueError("Input must be a non-negative integer")
if n == 0:
return 0
return n % 10 + sum_of_digits(n // 10)


if __name__ == "__main__":
import doctest

doctest.testmod()