TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
string_fibonacci.cpp
Go to the documentation of this file.
1
11#include <cstdint>
12#include <iostream>
13#ifdef _MSC_VER
14#include <string> // use this for MS Visual C
15#else
16#include <cstring> // otherwise
17#endif
18
25std::string add(std::string a, std::string b) {
26 std::string temp = "";
27
28 // carry flag
29 int carry = 0;
30
31 // fills up with zeros
32 while (a.length() < b.length()) {
33 a = "0" + a;
34 }
35
36 // fills up with zeros
37 while (b.length() < a.length()) {
38 b = "0" + b;
39 }
40
41 // adds the numbers a and b
42 for (int i = a.length() - 1; i >= 0; i--) {
43 char val = static_cast<char>(((a[i] - 48) + (b[i] - 48)) + 48 + carry);
44 if (val > 57) {
45 carry = 1;
46 val -= 10;
47 } else {
48 carry = 0;
49 }
50 temp = val + temp;
51 }
52
53 // processes the carry flag
54 if (carry == 1) {
55 temp = "1" + temp;
56 }
57
58 // removes leading zeros.
59 while (temp[0] == '0' && temp.length() > 1) {
60 temp = temp.substr(1);
61 }
62
63 return temp;
64}
65
69void fib_Accurate(uint64_t n) {
70 std::string tmp = "";
71 std::string fibMinus1 = "1";
72 std::string fibMinus2 = "0";
73 for (uint64_t i = 0; i < n; i++) {
74 tmp = add(fibMinus1, fibMinus2);
75 fibMinus2 = fibMinus1;
76 fibMinus1 = tmp;
77 }
78 std::cout << fibMinus2;
79}
80
82int main() {
83 int n;
84 std::cout << "Enter whatever number N you want to find the fibonacci of\n";
85 std::cin >> n;
86 std::cout << n << " th Fibonacci is \n";
87 fib_Accurate(n);
88
89 return 0;
90}
std::string add(std::string a, std::string b)
void fib_Accurate(uint64_t n)
int main()