Last active
April 5, 2025 17:09
-
-
Save unixnut/7cf83dfc2080bb4bd3520dd164785ee7 to your computer and use it in GitHub Desktop.
C++ Weekly - Ep 13 Fibonacci: You're Doing It Wrong
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <array> | |
| #include <utility> | |
| #include <sstream> | |
| template<int I> | |
| struct Fib | |
| { | |
| static const int val Fib<I-1>::val + Fib<I-2>::val; | |
| }; | |
| template<> | |
| struct Fib<0> | |
| { | |
| static const int val = 0; | |
| }; | |
| template<> | |
| struct Fib<1> | |
| { | |
| static const int val = 1; | |
| }; | |
| template<size_t ... I> | |
| const int fib_impl(std::index_sequence<I...>, const int i) | |
| { | |
| constexpr std::array<int, sizeof...(I)> a | |
| = {Fib<I>::val...}; | |
| return a[i]; | |
| } | |
| const int fib(const int i) | |
| { | |
| return fib_impl(std::make_index_sequence<47>(), i); | |
| } | |
| int main(int argc, const char *argv[]) | |
| { | |
| // Fixed value only | |
| //# std::cout << Fib<46>::val << '\n'; | |
| if (argc == 2) | |
| { | |
| std::stringstream ss(argv[1]); | |
| int i; | |
| ss >> i; | |
| std::cout << fib(i) << '\n'; | |
| } | |
| else | |
| { | |
| std::cerr << "fib-template: Invalid number of command line arguments" << '\n'; | |
| return 1; | |
| } | |
| // Added to avoid warning | |
| return 0; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example, written by Jason Turner and corrected by me, computes the Fibonacci sequence up to the limit associated with a long int, at compile time and puts it into an array that's indexable AT RUN TIME.