根据Fermat的小定理未获得预期的输出

问题描述

根据费马小定理,可以求出一个数的模乘乘法逆。

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

但是我在下面的程序中没有得到预期的输出。程序中哪个步骤错误?

 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

根据费马定理,两种情况下都应为3。

解决方法

base = (base*base)%MOD;

以上所有操作数均为int,因此计算以整数形式进行。但是(假设是32位整数)乘积base * base最终在循环过程中溢出了int范围。

以下强制转换是强制计算使用long long int并产生正确结果的一种方法。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...