I'm having a hard time understanding why
#include <iostream>
using namespace std;
int fib(int x) {
if (x == 1) {
return 1;
} else {
return fib(x-1)+fib(x-2);
}
}
int main() {
cout << fib(5) << endl;
}
results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number. E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!
in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1
Why not use iterative algorithm?
I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.
This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).
You should better use this approach or if you want to use recursion try this:
This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.
The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).
Change your code to
To include both 0 and 1.