We're all aware of Fibonacci sequence calculators but they look like C-style code. I want to avoid that and take advantage of the standard library. This code is very short, so I'm focusing on readability and correctness.
Barring comments, will people be able to understand the code just by looking at it?
As you're probably aware, this doesn't scale well due to stack limits. Using a dynamic memory approach, i.e.
auto arr = std::make_unique<type[]>(size);, this allocates A LOT of memory. Comparatively, an iterative approach doesn't need any memory allocation at all, as it doesn't store the previous results, only the last one. As a result, my approach is automatically slower. For example, this answerthis answer ran in under a second, while mine ran in 7 seconds for a size of1000000(and allocated 8,000,000 bytes).What's a way to make this faster AND to cut down on the memory usage?
I've compared the output to the oeis list and it seems correct. Would this break for bigger numbers? What should I replace
std::uint64_twith? While I needstd::uint64_tto store the bigger numbers, it obviously doubles the amount of memory allocated.
#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <cstdint>
int main()
{
std::array<std::uint64_t, 10000> arr;
arr.fill(0);
arr[1] = 1;
arr[2] = 1;
std::transform(arr.begin(), arr.end() - 2,
arr.begin() + 1, arr.begin() + 2,
std::plus<>());
std::copy(arr.begin(), arr.end(),
std::ostream_iterator<std::uint64_t>(std::cout, " "));
return 0;
}