From 99ee57e0a60c94d2a577218e85ef8d12570283fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Paw=C5=82owski?= Date: Wed, 31 Jan 2024 18:46:19 +0100 Subject: [PATCH 1/2] Add fibonacci functions iterative and recursive --- homework/fibonacci/fibonacci.hpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/homework/fibonacci/fibonacci.hpp b/homework/fibonacci/fibonacci.hpp index 3faab622..adc4fbf5 100644 --- a/homework/fibonacci/fibonacci.hpp +++ b/homework/fibonacci/fibonacci.hpp @@ -1,11 +1,32 @@ #pragma once int fibonacci_iterative(int sequence) { - // TODO: Your implementation goes here - return 0; + + unsigned result = 0; + unsigned a = 0, b = 1; + + for (unsigned i = 0; i < sequence; i++) + { + b = b + a; + a = b - a; + + result = a; + } + return result; } int fibonacci_recursive(int sequence) { - // TODO: Your implementation goes here - return 0; + + if (sequence == 0) + { + return 0; + } + else if (sequence < 3) + { + return 1; + } + else + { + return (fibonacci_recursive(sequence - 2) + fibonacci_recursive(sequence - 1)); + } } From 847c507c0e34acee1c00e31605dc80d954c4c98f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Paw=C5=82owski?= Date: Wed, 31 Jan 2024 19:02:55 +0100 Subject: [PATCH 2/2] Fix formatting --- homework/fibonacci/fibonacci.hpp | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/homework/fibonacci/fibonacci.hpp b/homework/fibonacci/fibonacci.hpp index adc4fbf5..9faf75a4 100644 --- a/homework/fibonacci/fibonacci.hpp +++ b/homework/fibonacci/fibonacci.hpp @@ -5,8 +5,7 @@ int fibonacci_iterative(int sequence) { unsigned result = 0; unsigned a = 0, b = 1; - for (unsigned i = 0; i < sequence; i++) - { + for (unsigned i = 0; i < sequence; i++) { b = b + a; a = b - a; @@ -17,16 +16,11 @@ int fibonacci_iterative(int sequence) { int fibonacci_recursive(int sequence) { - if (sequence == 0) - { + if (sequence == 0) { return 0; - } - else if (sequence < 3) - { + } else if (sequence < 3) { return 1; - } - else - { + } else { return (fibonacci_recursive(sequence - 2) + fibonacci_recursive(sequence - 1)); } }