#fibonucci sequence (command line argument)
1 messages · Page 1 of 1 (latest)
#include <iostream>
#include <vector>
// h/t to potterman28wxcv for a variant of this code
int fibonacci(int count) {
// We'll use a static std::vector to cache calculated results
static std::vector results{0, 1};
// If we've already seen this count, then use the cache'd result
if (count < static_cast<int>(std::size(results)))
return results[count];
// Otherwise calculate the new result and add it
results.push_back(fibonacci(count - 1) + fibonacci(count - 2));
return results[count];
}
// And a main program to display the first 13 Fibonacci numbers
int main() {
for (int count{0}; count < 13; ++count)
std::cout << fibonacci(count) << ' ';
return 0;
}
In main, count is initialized with 0 so in the function call
Fibonacci(count)
Its fibonacci(0)
Then its passed to the function fibonacci afterwards
In the function fibonnaci
Fibonucci(count-1) + fibonucci(count-2)
Is Fibonucci(0-1) + fibonucci(0-2)
= -3
So return now is -3
Then -3 should be printed out first.
I dont understand this code the first digits were printed were 0 1 1 2 3 5 8 13 21 34 55 89 144
Isn't the first digit -3 ??
Please dont select every tags like you did. Select only the ones related to your issue.
I cant untagged though
Yes you can via the setting of the post but it's ok for this time, I removed the unnecessary tags
With out my permission?
No it's 0. This code uses a static vectors to cache the results of the calculation, this allows it to skip calculation when it's already been done making the process much faster. You can see that the cache is initialized with 2 default values, 0 and 1. Since what you've 0 is smaller than the length of the list, it means that it is contained in the list, so instead of going through calculating 0, it returns it (return results[count]). The same thing will happen with 1.
Yes. If you think I removed a tag that is related to your issue you can add it back.
You know c++?
Just a little bit but I know programming so it doesn't really matter and it's a common technique. Plus the comments are pretty easy to understand.
But my text at the top you understood what I said right ??
Yea I think I understood your confusion which I think I answered properly in my explanation