Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
string_fibonacci.cpp File Reference

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

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

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

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
24  {
25  std::string temp = "";
26 
27  // carry flag
28  int carry = 0;
29 
30  // fills up with zeros
31  while (a.length() < b.length()) {
32  a = "0" + a;
33  }
34 
35  // fills up with zeros
36  while (b.length() < a.length()) {
37  b = "0" + b;
38  }
39 
40  // adds the numbers a and b
41  for (int i = a.length() - 1; i >= 0; i--) {
42  char val = static_cast<char>(((a[i] - 48) + (b[i] - 48)) + 48 + carry);
43  if (val > 57) {
44  carry = 1;
45  val -= 10;
46  } else {
47  carry = 0;
48  }
49  temp = val + temp;
50  }
51 
52  // processes the carry flag
53  if (carry == 1) {
54  temp = "1" + temp;
55  }
56 
57  // removes leading zeros.
58  while (temp[0] == '0' && temp.length() > 1) {
59  temp = temp.substr(1);
60  }
61 
62  return temp;
63 }
Here is the call graph for this function:

◆ fib_Accurate()

void fib_Accurate ( uint64_t  n)

Fibonacci iterator

Parameters
[in]nn^th Fibonacci number
68  {
69  std::string tmp = "";
70  std::string fibMinus1 = "1";
71  std::string fibMinus2 = "0";
72  for (uint64_t i = 0; i < n; i++) {
73  tmp = add(fibMinus1, fibMinus2);
74  fibMinus2 = fibMinus1;
75  fibMinus1 = tmp;
76  }
77  std::cout << fibMinus2;
78 }
Here is the call graph for this function:

◆ main()

int main ( void  )

main function

81  {
82  int n;
83  std::cout << "Enter whatever number N you want to find the fibonacci of\n";
84  std::cin >> n;
85  std::cout << n << " th Fibonacci is \n";
86  fib_Accurate(n);
87 
88  return 0;
89 }
Here is the call graph for this function:
std::string
STL class.
std::string::length
T length(T... args)
std::cout
std::string::substr
T substr(T... args)
add
std::string add(std::string a, std::string b)
Definition: string_fibonacci.cpp:24
fib_Accurate
void fib_Accurate(uint64_t n)
Definition: string_fibonacci.cpp:68
std::cin