【问题标题】:Not getting expected output as per Fermat's little theorem根据费马小定理没有得到预期的输出
【发布时间】:2021-02-22 01:40:33
【问题描述】:

根据费马小定理,可以找到一个数的模乘逆如下

 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。

【问题讨论】:

  • 不是费马小定理。费马小定理要求 m 是素数,而不仅仅是 a 的互素数。

标签: c++ math multiplication modulo inverse


【解决方案1】:
base = (base*base)%MOD;

上面的所有操作数都是int,所以计算是以整数进行的。但是(假设为 32 位整数)乘积 base * base 最终会在循环期间溢出 int 范围。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多