当我们将变量“ u”的数据类型从long long更改为int时,为什么模幂运算会出错?

时间:2019-07-09 15:44:07

标签: c++ integer long-integer modular-arithmetic

当变量“ u”的数据类型很长时,模幂运算效果很好,但是当将其更改为int时,会给出错误的答案。

例如,当(2,447,1e9 + 7)作为参数传递时,“ long long u”给出941778035作为答案,而“ int u”给出0作为答案。功能如下:-

int modpow(int x, int n, int m) {  //to calculate x^n%m
    if (n == 0) return 1%m;
    long long u = modpow(x,n/2,m);
    u = (u*u)%m;
    if (n%2 == 1) u = (u*x)%m;
    return u;
}
int modpow(int x, int n, int m) {  //to calculate x^n%m
    if (n == 0) return 1%m;
    int u = modpow(x,n/2,m);
    u = (u*u)%m;
    if (n%2 == 1) u = (u*x)%m;
    return u;
}
int main(){    //used as main in program with x = 2 and m = 1e9+7 and n is given by user
   int n, m = 1e9+7;
   cin>>n;
   int pow = modpow(2,n,m);
   cout<<pow;
   return 0;
}

1 个答案:

答案 0 :(得分:0)

考虑modpow(1e9, 2, 1e9+7)

if (2 == 0) // no
int u = modpow(1e9, 1, 1e9+7);

  if (1 == 0) // no
  int u = modpow(1e9, 0, 1e9+7);

    if (0 == 0) return 1;

  int u = 1;
  u = 1; // (1*1) % (1e9+7)
  if (1 % 2 == 1) u = 1e9; // (1 * 1e9) % (1e9+7)

int u = 1e9;
u = (1e9 * 1e9)%(1e9+7); // OUCH!
如果int u仅32位宽,

1e9 * 1e9就会溢出,在大多数现代计算机环境中(见https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models)就是