#fibonucci sequence (command line argument)

1 messages · Page 1 of 1 (latest)

merry marten
#

Fy

#
#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;
}
merry marten
merry marten
#

Isn't the first digit -3 ??

opaque current
#

Please dont select every tags like you did. Select only the ones related to your issue.

opaque current
#

Yes you can via the setting of the post but it's ok for this time, I removed the unnecessary tags

opaque current
# merry marten Isn't the first digit -3 ??

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.

opaque current
opaque current
#

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.

merry marten
opaque current