Advertisement
knightL

Fibonacci

Jun 3rd, 2015
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cassert>
  4. #include <cstring>
  5. #include <cstdlib>
  6. #include <cmath>
  7. #include <algorithm>
  8. #include <vector>
  9. #include <string>
  10. #include <iostream>
  11. #include <queue>
  12. #include <set>
  13. #include <map>
  14. using namespace std;
  15.  
  16. int MOD;
  17. typedef long long ll;
  18.  
  19. ll gcd(ll a, ll b)
  20. {
  21.     return b?gcd(b,a%b):a;
  22. }
  23.  
  24. map<ll,ll> phiMP;
  25. ll phi(ll n)
  26. {
  27.     if(!phiMP.count(n))
  28.     {
  29.         ll res=1;
  30.         ll t=n;
  31.         for(ll i=2;i*i<=t;i++)
  32.         {
  33.             if(t%i==0)
  34.             {
  35.                 res*=i-1;
  36.                 t/=i;
  37.                 while(t%i==0)
  38.                 {
  39.                     t/=i;
  40.                     res*=i;
  41.                 }
  42.             }
  43.         }
  44.         if(t!=1) res*=t-1;
  45.         phiMP[n]=res;
  46.     }
  47.     return phiMP[n];
  48. }
  49.  
  50. template<typename T>
  51. T qpowmod(T a, ll b, ll mod)
  52. {
  53.     T res=1;
  54.     while(b)
  55.     {
  56.         if(b&1) res=res*a%mod;
  57.         a=a*a%mod;
  58.         b>>=1;
  59.     }
  60.     return res;
  61. }
  62.  
  63. struct Ratio
  64. {
  65.     ll a, b;
  66.     Ratio(ll a=0, ll b=0):a(a),b(b)
  67.     {
  68.     }
  69.     Ratio operator+(const Ratio& y) const
  70.     {
  71.         return Ratio(a+y.a, b+y.b);
  72.     }
  73.     Ratio operator-(const Ratio& y) const
  74.     {
  75.         return Ratio(a-y.a, b-y.b);
  76.     }
  77.     Ratio operator*(const Ratio& y) const
  78.     {
  79.         return Ratio(a*y.a+5*b*y.b, a*y.b+b*y.a);
  80.     }
  81.     Ratio operator%(ll mod) const
  82.     {
  83.         return Ratio(a%mod, b%mod);
  84.     }
  85.     ll Re() const
  86.     {
  87.         return a;
  88.     }
  89.     ll Im() const
  90.     {
  91.         return b;
  92.     }
  93. };
  94.  
  95. ll revmod(ll a, ll MOD)
  96. {
  97.     return qpowmod(a,phi(MOD)-1,MOD);
  98. }
  99.  
  100. ll fib(ll n)
  101. {
  102.     return (qpowmod<Ratio>(Ratio(1,1)*revmod(2,MOD),n,MOD)).Im()*2%MOD;
  103. }
  104.  
  105. int main()
  106. {
  107.     int n;
  108.     scanf("%d%d",&n,&MOD);
  109.     printf("%lld\n",fib(n));
  110.     return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement