Skip to content
The site is in test mode. All features are free for now.
MathAgora

C++ and Mathematics

Functions and recursion

Defining and calling functions, pass by value vs by reference, recursion: factorial, Fibonacci, fast power, digit sum.

55 min 8 questions

01Functions

The mathematical function f(x)=2x+1f(x) = 2x + 1 looks like this in C++: int f(int x) { return 2 * x + 1; }. f(f(3)) is exactly the composition f(f(3))f(f(3)).

Pass by value (int x): the function gets a copy and cannot change the caller's variable. Pass by reference (int &x): the function works on the original.

02Recursion

A recursive function calls itself — the code version of induction or a recurrence: n!=n⋅(n−1)!n! = n\cdot(n - 1)!, Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}. A base case (e.g. 0!=10! = 1) is essential, otherwise the recursion never ends.

The naive fib(n) makes exponentially many calls because it recomputes the same values; with a loop or memoization it runs in linear time.

Fast power: be=(be/2)2b^e = (b^{e/2})^2 for even ee and b⋅(b⌊e/2⌋)2b\cdot(b^{\lfloor e/2\rfloor})^2 for odd ee — it takes about log⁡2e\log_2 e steps.

C++
long long fact(int n) {
    if (n <= 1) return 1;        // base case
    return n * fact(n - 1);      // n! = n * (n-1)!
}

Key formulas

  • Factorial recursion

    n!=n⋅(n−1)!,0!=1n!=n\cdot(n-1)!,\quad 0!=1
  • Fibonacci numbers

    F0=0, F1=1, Fn=Fn−1+Fn−2F_0=0,\ F_1=1,\ F_n=F_{n-1}+F_{n-2}
  • Fast exponentiation

    be={(be/2)2,e≡0(mod2)b (b(e−1)/2)2,e≡1(mod2)b^e=\begin{cases}(b^{e/2})^2,& e\equiv0\pmod2\\ b\,(b^{(e-1)/2})^2,& e\equiv1\pmod2\end{cases}

Worked examples

Example 1

How many calls does fact(5) make (including itself)?

C++
fact(5) -> fact(4) -> fact(3) -> fact(2) -> fact(1)