summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/01-intro/01-fibonacci
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 20:29:59 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 20:29:59 +0100
commit0f13a35dee0df21f4c1a387b50582a958c7bc439 (patch)
treed5e7e2d59ea9a709b660d94428ea951a80f085ba /01-algorithmic_toolbox/01-intro/01-fibonacci
parent13eab863735725f9a02cd4ae0b1c25725cc27569 (diff)
downloadcoursera-0f13a35dee0df21f4c1a387b50582a958c7bc439.zip
coursera-0f13a35dee0df21f4c1a387b50582a958c7bc439.tar.gz
Algorithms : complete 01-algorithmic_toolbox 01-intro
Diffstat (limited to '01-algorithmic_toolbox/01-intro/01-fibonacci')
-rw-r--r--01-algorithmic_toolbox/01-intro/01-fibonacci/fibonacci.cpp19
1 files changed, 18 insertions, 1 deletions
diff --git a/01-algorithmic_toolbox/01-intro/01-fibonacci/fibonacci.cpp b/01-algorithmic_toolbox/01-intro/01-fibonacci/fibonacci.cpp
index adc7404..c2564b8 100644
--- a/01-algorithmic_toolbox/01-intro/01-fibonacci/fibonacci.cpp
+++ b/01-algorithmic_toolbox/01-intro/01-fibonacci/fibonacci.cpp
@@ -7,10 +7,27 @@ int calc_fib(int n) {
return calc_fib(n - 1) + calc_fib(n - 2);
}
+int fib(int n)
+{
+ int a, b, c, i;
+
+ if (n <= 1)
+ return n;
+
+ a = 0; b = 1;
+ for(i = 1; i < n; i++) {
+ c = a + b;
+ a = b;
+ b = c;
+ }
+
+ return b;
+}
+
int main() {
int n = 0;
std::cin >> n;
- std::cout << calc_fib(n) << '\n';
+ std::cout << fib(n) << '\n';
return 0;
}