//******************************************************** // The following code example is taken from the book // C++23 - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppstd23.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include #include std::generator fibonacci(int num) { if (num < 1) co_return; // end coroutine if no numbers requested // first two numbers are 1: long a = 1; co_yield a; // SUSPEND with first number if (num < 2) co_return; // end coroutine if one number requested long b = 1; co_yield b; // SUSPEND with second number // loop over the remaining num-2 sums of previous two numbers: for (int i = 2; i < num; ++i) { auto sum = a + b; co_yield sum; // SUSPEND with sum of previous two numbers a = std::exchange(b, sum); } }