Advertisement
vovanhoangtuan

Tìm Fibo thứ n

May 28th, 2020
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void fillZero(string &a, string &b)
  6. {
  7.     int lengthMax = max(a.length(), b.length());
  8.     while (a.length() < lengthMax) a = '0' + a;
  9.     while (b.length() < lengthMax) b = '0' + b;
  10. }
  11.  
  12. int SoSanh(string a, string b)
  13. {
  14.     if (a.length() > b.length()) return 1;
  15.     else if (a.length() < b.length()) return -1;
  16.  
  17.     for (int i = 0; i < a.length(); i++)
  18.     {
  19.         int x = a[i] - 48;
  20.         int y = b[i] - 48;
  21.         if (x > y) return 1;
  22.         else if (x < y )return -1;
  23.     }
  24.     return 0;
  25. }
  26.  
  27. string Cong(string a, string b)
  28. {
  29.     int du = 0;
  30.     string res = "";
  31.     fillZero(a, b);
  32.     for (int i = a.length() - 1; i >= 0; i--)
  33.     {
  34.         int x = a[i] -48;
  35.         int y = b[i] -48;
  36.         int temp = x + y + du;
  37.         if ( i == 0)
  38.         {
  39.             stringstream ss;
  40.             string s;
  41.             ss << temp;
  42.             ss >> s;
  43.             res = s + res;
  44.             break;
  45.         }
  46.         res = (char)(temp % 10 + 48) + res;
  47.         du = temp / 10;
  48.     }
  49.     while (res.length() > 1 && res[0] == '0') res.erase(0, 1);
  50.     return res;
  51. }
  52.  
  53.  
  54. string genFibo(int n)
  55. {
  56.     string f1 = "1", f2 = "1", f3 = "2";
  57.     if (n == 1 || n == 2 ) return f1;
  58.     for (int i = 3; i <= n; i++)
  59.     {
  60.         f3 = Cong(f1, f2);
  61.         f1 = f2;
  62.         f2 = f3;
  63.     }
  64.     return f3;
  65. }
  66.  
  67.  
  68. int main()
  69. {
  70.     cin.tie(0);
  71.     ios_base::sync_with_stdio(0);
  72.     int n;
  73.     cin >> n;
  74.     cout << genFibo(n);
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement