Created
April 3, 2025 19:31
-
-
Save fabiogaluppo/1e9a6149c34ae4192a17999eee5347bf to your computer and use it in GitHub Desktop.
Fibonacci numbers with custom generator for C++20
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
//Source code C++ MasterClass (Algorithms with C++ MasterClass) by Fabio Galuppo | |
//C++ MasterClass - https://www.linkedin.com/company/cppmasterclass - https://cppmasterclass.com.br/ | |
//Fabio Galuppo - http://member.acm.org/~fabiogaluppo - [email protected] | |
//March 2025 | |
//g++ -O3 -std=c++20 _demo_generator.cpp -o a.exe | |
//cl /Fo.\obj\ /EHsc /O2 /std:c++20 _demo_generator.cpp /link /out:a.exe | |
#include <iomanip> | |
#include <iostream> | |
#include "Generator.hpp" | |
//https://oeis.org/A000045 | |
Generator<unsigned long long> fibonacci_numbers(unsigned short n) | |
{ | |
unsigned long long a = 0, b = 1; | |
co_yield a; | |
while (n-- > 0) | |
{ | |
co_yield b; | |
b += a; | |
a = b - a; | |
} | |
} | |
int main() | |
{ | |
for (unsigned short n = 0; n <= 16; ++n) | |
{ | |
std::cout << "Fib(" << std::setw(2) << n << "): "; | |
auto gen = fibonacci_numbers(n); | |
while (auto opt = gen.next()) | |
std::cout << *opt << ' '; | |
std::cout << '\n'; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment