Last active 1702976240

Fibonacci in C++

anduin's Avatar anduin revised this gist 1702976240. Go to revision

1 file changed, 2 insertions, 6 deletions

main.cpp

@@ -1,24 +1,20 @@
1 1 #include <iostream>
2 2 #include <functional>
3 -
4 3 std::function<int()> fibonacci()
5 4 {
6 5 int current = 1, next = 1;
7 -
8 6 return [=]() mutable {
9 7 int result = current;
10 - next = current + (current = next);
8 + current = next;
9 + next = current + result;
11 10 return result;
12 11 };
13 12 }
14 -
15 13 int main()
16 14 {
17 15 auto fib = fibonacci();
18 -
19 16 for (int i = 0; i < 10; i++) {
20 17 std::cout << fib() << std::endl;
21 18 }
22 -
23 19 return 0;
24 20 }

anduin's Avatar anduin revised this gist 1702408992. Go to revision

No changes

anduin's Avatar anduin revised this gist 1702407339. Go to revision

1 file changed, 1 insertion, 1 deletion

main.cpp

@@ -1,7 +1,7 @@
1 1 #include <iostream>
2 2 #include <functional>
3 3
4 - std::function<int()> fibonacci()W
4 + std::function<int()> fibonacci()
5 5 {
6 6 int current = 1, next = 1;
7 7

anduin's Avatar anduin revised this gist 1702407324. Go to revision

1 file changed, 4 deletions

main.cpp

@@ -1,5 +1,3 @@
1 -
2 - ```cpp
3 1 #include <iostream>
4 2 #include <functional>
5 3
@@ -24,5 +22,3 @@ int main()
24 22
25 23 return 0;
26 24 }
27 -
28 - ```

anduin revised this gist 1702407222. Go to revision

1 file changed, 28 insertions

main.cpp(file created)

@@ -0,0 +1,28 @@
1 +
2 + ```cpp
3 + #include <iostream>
4 + #include <functional>
5 +
6 + std::function<int()> fibonacci()W
7 + {
8 + int current = 1, next = 1;
9 +
10 + return [=]() mutable {
11 + int result = current;
12 + next = current + (current = next);
13 + return result;
14 + };
15 + }
16 +
17 + int main()
18 + {
19 + auto fib = fibonacci();
20 +
21 + for (int i = 0; i < 10; i++) {
22 + std::cout << fib() << std::endl;
23 + }
24 +
25 + return 0;
26 + }
27 +
28 + ```
Newer Older