|
|
|
|
|
by sp332
4434 days ago
|
|
Well, that's because it's an awful way to calculate a fibonacci number! At least you could memoize the function, remembering what the (n-1) number was instead of recalculating every time. Or, since you only need the last 2 numbers to keep going, forget everything but those 2: unsigned long long fib(int a) {
unsigned long long x, y, temp;
while (a > 0) {
temp = x;
x = y;
y = y + temp;
--a;
}
return y;
}
This is much faster and won't blow up your stack. |
|
To be more precise, it is an inefficient method of calculating a Fibonacci number. Using your function, if you were to measure the execution time of fib(n), then divide it by the execution time of fib(n-1), would you get a more precise value of the Golden ratio?
> This is much faster and won't blow up your stack quite so much.
Or we could use an iterative version ... wait up your code changed to an iterative implementation. Man that's weird.
EDIT:
Your code:
I just noticed: x, y and temp have not been initialised.