return
values to communicate their
resultsRecursion is the term for functions calling themselves
Recursion consists of
#include <cstdint>
#include <iostream>
uint64_t factorial(uint32_t n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursion
}
int main() {
std::cout << "factorial(5): " << factorial(5) << std::endl;
return 0;
}
#include <cstdint>
#include <cstdlib>
#include <iostream>
uint64_t fib(uint32_t n) {
if (n <= 1) return n; // base case
return fib(n - 1) + fib(n - 2); // recursion (overlapping subproblems)
}
int main(int argc, char** argv) {
uint32_t n{6}; // default value
if (argc == 2) { n = std::atoi(argv[1]); }
std::cout << "fib(" << n << "): " << fib(n) << std::endl;
return 0;
}
Download fibonacci.cpp
Allows to speed up computer programs by re-using stored results of expensive function calls to pure functions
Ideally, we wouldn't modify the original function
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <map>
uint64_t fib(uint32_t n) {
static std::map<uint32_t, uint64_t> cache;
if (not cache.contains(n)) {
if (n <= 1) cache[n] = n; // base case
else cache[n] = fib(n - 1) + fib(n - 2); // recursion
}
return cache[n];
}
int main(int argc, char** argv) {
uint32_t n{6}; // default value
if (argc == 2) { n = std::atoi(argv[1]); }
std::cout << "fib(" << n << "): " << fib(n) << std::endl;
return 0;
}
Download cached_fibonacci.cpp