Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string findSum(string str1, string str2)
  5. {
  6.     if (str1.length() > str2.length())
  7.     {
  8.         swap(str1, str2);
  9.     }
  10.  
  11.     string str = "";
  12.     long long int n1 = str1.length(), n2 = str2.length(), carry = 0;
  13.  
  14.     reverse(str1.begin(), str1.end());
  15.     reverse(str2.begin(), str2.end());
  16.  
  17.     for (long long int i = 0; i < n1; i++)
  18.     {
  19.         long long int sum = ((str1[i] - '0') + (str2[i] - '0') + carry);
  20.         str.push_back(sum % 10 + '0');
  21.         carry = sum / 10;
  22.     }
  23.  
  24.     for (long long int i = n1; i < n2; i++)
  25.     {
  26.         long long int sum = ((str2[i] - '0') + carry);
  27.         str.push_back(sum % 10 + '0');
  28.         carry = sum / 10;
  29.     }
  30.  
  31.     if (carry)
  32.     {
  33.         str.push_back(carry + '0');
  34.     }
  35.  
  36.     reverse(str.begin(), str.end());
  37.  
  38.     return str;
  39. }
  40.  
  41. int main()
  42. {
  43.     ios_base::sync_with_stdio(false);
  44.     cin.tie(NULL);
  45.     long long int count;
  46.     while (cin >> count && count != EOF)
  47.     {
  48.         string a, b, ans;
  49.         a = "0";
  50.         b = "1";
  51.         for (long long int i = 3; i <= count + 1; i++)
  52.         {
  53.             ans = b;
  54.             b = findSum(a, b);
  55.             a = ans;
  56.         }
  57.         cout << "The Fibonacci number for " << count << " is " << b << endl;
  58.     }
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement