TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
string_fibonacci.cpp
Go to the documentation of this file.
1
10
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
25
std::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
69
void
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
82
int
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
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
fib_Accurate
void fib_Accurate(uint64_t n)
Definition
string_fibonacci.cpp:69
add
std::string add(const std::string &first, const std::string &second)
Adding two string.
Definition
uint128_t.hpp:31
math
string_fibonacci.cpp
Generated by
1.18.0