From 0256f9edd8ce62e78de3d6703701a5e91ab21e08 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Tue, 27 Mar 2018 18:51:25 +0200 Subject: [PATCH] improved the code and put in some comments --- Others/String Fibonacci.cpp | 55 +++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/Others/String Fibonacci.cpp b/Others/String Fibonacci.cpp index 77571b93a..44d5d5748 100644 --- a/Others/String Fibonacci.cpp +++ b/Others/String Fibonacci.cpp @@ -8,65 +8,78 @@ using namespace std; -string add(string a, string b) -{ +string add(string a, string b) +{ string temp = ""; - while ((int)a.length() < (int)b.length()) + + // carry flag + int carry = 0; + + // fills up with zeros + while ((int)a.length() < (int)b.length()) { a = "0" + a; } - while ((int)b.length() < (int)a.length()) { + + // fills up with zeros + while ((int)b.length() < (int)a.length()) + { b = "0" + b; } - int carry = 0; - for (int i = a.length() - 1; i >= 0; i--) + + // adds the numbers a and b + for (int i = a.length() - 1; i >= 0; i--) { char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) + if (val > 57) { carry = 1; val -= 10; } - else + else { carry = 0; } temp = val + temp; } - if (carry != 0) + + // processes the carry flag + if (carry == 1) { temp = "1" + temp; } - while (temp[0] == '0' && temp.length() != 1) + + // removes leading zeros. + while (temp[0] == '0' && temp.length() > 1) { temp = temp.substr(1); } + return temp; } -void fib_Accurate(long long n) +void fib_Accurate(long long n) { string tmp = ""; string fibMinus1 = "1"; string fibMinus2 = "0"; - for (long long i = 0; i < n; i++) - { - tmp = add(fibMinus1, fibMinus2); - - fibMinus2 = fibMinus1; - fibMinus1 = tmp; - } + for (long long i = 0; i < n; i++) + { + tmp = add(fibMinus1, fibMinus2); + fibMinus2 = fibMinus1; + fibMinus1 = tmp; + } cout << fibMinus2; } -int main() +int main() { int n; cout << "Enter whatever number N you want to find the fibonacci of\n"; cin >> n; cout << n << " th Fibonacci is \n"; - fib_Accurate(n); - + fib_Accurate(n); + return 0; }