Search code examples
c++mathmultiplicationmoduloinverse

Not getting expected output as per Fermat's little theorem


According to Fermat's little theorem the modulo multiplicative inverse of a number can be found as below

 a^(m-2) mod m if a and m are co-prime.

But I am not getting expected output in below program. Which is the wrong step in procedure?

 int pow_mod(int base,int pow,int MOD){
     long long int res = 1;
     while(pow){
       if(pow%2){
          res = (res*base)%MOD;
          pow--;
       }else{
          base = (base*base)%MOD;
          pow/=2;
       }
   }
   return res;
}
int main() {
   int mod = 100000007;
   cout<<(33 * pow_mod(11,mod-2,mod) ) %mod<<"\n";
    cout<<(33 / 11 ) %mod;

   return 0;
}

The Actual output : 
 
19692016
3

It should have been 3 in both case according to Fermat's theorem.


Solution

  • base = (base*base)%MOD;
    

    All operands in the above are int so the calculation is done in integers. But (assuming 32-bit integers) the product base * base eventually overflows the int range during the loop.

    The following cast is one way to force the calculation to use long long int and produces the correct result.

    base = (base * (long long int)base) % MOD;