Linkon
Linkon

Reputation: 1168

How to find modular multiplicative inverse in c++

#include <bits/stdc++.h>

#define mx 1000005
#define mod 1000003

using namespace std;

long long arr[mx];

int fact()
{
    arr[0]=1;
    for(int i=1; i<mx; i++)
    {
        arr[i]=((i%mod)*(arr[i-1]%mod))%mod;
    }
}

int main()
{
    int t;
    long long a,b,C,E;
    fact();
    cin>>t;
    while(t--)
    {
        cin>>a>>b;

        C=(arr[a]%mod)%mod;
        E=((arr[b])%mod)*((arr[a-b])%mod)%mod;
    }

}

In this problem i have to calculate (C/E)%1000003. How could i do this using modular multiplicative inverse technique ? Is there other way to calculate this ?

Upvotes: 4

Views: 10232

Answers (1)

v78
v78

Reputation: 2933

Since 1000003 is prime.

long long mod = 1000003;
inline long long mpow(long long b, long long ex){
    if (b==1)return 1;
    long long r = 1;
    while (ex ){
        if (ex&1)r=(r * b)%mod;
        ex = ex >> 1;
        b = (b * b)%mod;}
    return r;
}

Then do

inverse of E % mod is = mpow(E,mod-2)

Fermats's little theorem

geekforgeeks

Upvotes: 5

Related Questions