Recursion (Programming)
tags
#cs
Recursively-defined Functions
In Python
Let $f(n)$ return the result of $$ \sum _{i=0}^ni $$ $f(n)$ can also be defined recursively as so: $$ f(n) = \begin{cases} 0, & n=0 \\ f(n-1)+n, & n>0 \end{cases} $$
def f(n: int) -> int:
"""Return the sum of the numbers between 0 and n, inclusive.
Preconditions:
- n >= 0
>>> f(4)
10
"""
if n == 0:
return 0
else:
return f(n - 1) + n