TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
string_fibonacci.cpp File Reference

This Programme returns the Nth fibonacci as a string. More...

#include <cstdint>
#include <iostream>
#include <cstring>
Include dependency graph for string_fibonacci.cpp:

Go to the source code of this file.

Functions

std::string add (std::string a, std::string b)
 
void fib_Accurate (uint64_t n)
 
int main ()
 

Detailed Description

This Programme returns the Nth fibonacci as a string.

The method used is manual addition with carry and placing it in a string which is called string addition This makes it have no bounds or limits

See also
fibonacci_large.cpp, fibonacci_fast.cpp, fibonacci.cpp

Definition in file string_fibonacci.cpp.

Function Documentation

◆ add()

std::string add ( std::string a,
std::string b )

function to add two string numbers

Parameters
[in]afirst number in string to add
[in]bsecond number in string to add
Returns
sum as a std::string

Definition at line 25 of file string_fibonacci.cpp.

25 {
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}

◆ fib_Accurate()

void fib_Accurate ( uint64_t n)

Fibonacci iterator

Parameters
[in]nn^th Fibonacci number

Definition at line 69 of file string_fibonacci.cpp.

69 {
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}
std::string add(std::string a, std::string b)

◆ main()

int main ( void )

main function

Definition at line 82 of file string_fibonacci.cpp.

82 {
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}
void fib_Accurate(uint64_t n)