Multiplicative inverse finishing

Multiplicative inverse

1. Fermat's Little Theorem

If $ a, P $ prime, then $ a ^ {p-1} ≡ 1 (mod p) $
and $ a known equation by the inverse of x ≡ 1 (mod p) $ , to give $ a x≡ A ^ { p-1} (mod p) $
so as inverse $ X $ $ a ^ {p-2} mod p $, fast power to solve.

    #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. Linear inversing

This is not evidence.
But will not permit problem is not large, can be directly used as a conclusion.
$ Inv [i] = p - \ frac {p} {i} * inv [p mod i] mod p $
Note, however $ INV [. 1] =. 1, INV [0] = tan90 ^ O = 0 $
$ for $ 2 cycle from the start, the time complexity $ 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;
  }

Guess you like

Origin www.cnblogs.com/Repulser/p/11207140.html