乗法逆仕上げ

逆数

1.フェルマーの小定理

$、Pの$プライムし、$ ^ {P-1}もし ≡1(MOD P)$
と$の逆数で知ら式X≡1(MOD P)$は 、 得$ x≡のA ^ { P-1}(MOD P) $
逆の$ Xの$する$ A ^ {P-2}ように MODのP $、 高速電力が解決します。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    
    using namespace std;
    
    #define LL long long
    
    LL n,p;
    
    inline LL fast_pow(LL a,LL b,LL p) {
        LL ans = 1;
        a %= p;
        while(b) {
            if(b&1) ans = ans * a % p;
            a = a * a % p;
            b >>= 1;
        }
        ans %= p;
        return ans;
    }
    
    int main() {
        scanf("%lld%lld",&n,&p);
        for(int i = 1 ; i <= n ; i++) 
            printf("%lld \n",fast_pow(i,p-2,p));
        return 0;
    }

2.リニア反転さ

これは証拠ではありません。
しかし、問題が大きくない許可、直接結論として使用することができません。
$ Invの[I] = P - \ FRAC {P} {I} * INV [PのMOD I] MOD Pする$
。ただし$ INV [1] = 1、INV [0] = tan90 ^ O = 0 $
$のために$ 2サイクル開始から、時間複雑$ O(N)$。


  
  using namespace std;
  
  #define LL long long
  const int N = 3e6 + 10;
  
  LL n,p,inv[N];
  
  int main() {
      scanf("%lld%lld",&n,&p);
      inv[1] = 1;inv[0] = 0;
      for(int i = 2; i <= n ; i++) 
          inv[i] = p - (p / i) * inv[p % i] % p;
      for(int i = 1 ; i <= n ; i++)
          printf("%lld \n",inv[i]);
      return 0;
  }

おすすめ

転載: www.cnblogs.com/Repulser/p/11207140.html