Advertisement
Riz1Ahmed

Moduler Inverse by Me

Dec 11th, 2019
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. /********************
  2. Riz1 Ahmed, CSE, LU.
  3. ********************/
  4. #include<bits/stdc++.h>
  5. /**
  6. Problem: (A/B)*C mod P.
  7. Constraint: A=B=C=P=1e8;
  8.  
  9. Here you will get WA if apply this formula
  10. normally like (((A/B)%P)*C)%P
  11.  
  12. (A/B)*C = A*(1/B)*C = A*B^-1*C.
  13.  
  14. Here B^-1 we say Inverse of B or B Inverse.
  15. and that is called Modular Inverse :).
  16. B^-1=modInverse(B,P).
  17.  
  18. So have to apply like (a*modInverse(B,P)%P)*C)%P
  19. */
  20.  
  21. ///a^n mod M
  22. ll PowerMod(ll a,ll n,ll M){
  23.     if (!n) return 1;
  24.     ll x=PowerMod(a,n/2,M);
  25.     x=(x*x)%M;
  26.     return (n&1)? (x*a)%M : x;
  27. }
  28. ll modInverseByPw(ll n,ll M){
  29.     /// return n^(-1) mod M
  30.     return PowerMod(n,M-2,M);
  31. }
  32.  
  33. ll gcdExtended(ll a, ll b, ll &x, ll &y){
  34.     if (!a){x=0, y=1; return b;}
  35.     ll x1, y1;
  36.     ll gcd = gcdExtended(b%a, a, x1, y1);
  37.     x = y1-(b/a)*x1;
  38.     y = x1;
  39.     return gcd;
  40. }
  41. ll modInverseByGCD(ll a) {
  42.     ll x,y;///if a=0 not exist
  43.     ll g = gcdExtended(a,M,x,y);
  44.     if (g==1) return (x%M+M)%M;
  45.     printf("%d=ModInv not exist\n",a);
  46. }
  47. int main(){
  48.     ll A,B,C,P;
  49.     A=123, B=23, C=23, P=1e9+7;
  50.     cout<< (A*modInverseByPw(B,P)%P)*C)%P<<endl;
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement