Snippet. Vala. Calculating the Fibonachi Numbers

The following Vala function will calculate the Fibonacci numbers.

long fibonacci(int n){
    if (n < 2) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

The function will become increasingly slower with bigger numbers. Also keep in mind that at some point (about the number 90) it will overflow a long.

Example

for(int i=0; i<10; i++) {
    stdout.printf(fibonacci(i).to_string());
}

Updated on: 23 Nov 2024