Recursion

$$ \mathrm{fibonacci}(a, b, i) = \left\{ \begin{array}{ll} a, & \mathrm{if} \ {i = {1}} \\ b, & \mathrm{if} \ {i = {2}} \\ \mathrm{fibonacci}\left(a, b, i - {1}\right) + \mathrm{fibonacci}\left(a, b, i - {2}\right), & \mathrm{otherwise} \end{array} \right. $$

Python

def fibonacci(a, b, i):
    if i == 1:
        return a
    elif i == 2:
        return b
    else:
        return fibonacci(a, b, i-1) + fibonacci(a, b, i-2)

C

int fibbonacci(a, b, i) {
     if(i == 1) return a;
     else if(i == 2) return b;
     else return(fibbonacci(a, b, i-1) + fibbonacci(a, b, i-2));
}

Rust

fn fibonacci(a: i32, b: i32, i: i32) -> i32 {
    if i == 1 {
        a
    } else if i == 2 {
        b
    } else {
        fibonacci(a, b, i - 1) + fibonacci(a, b, i - 2)
    }
}
Previous
Next