利用模函数实现乘幂

Using modulo function to implement power with multiply

本文关键字:实现 函数      更新时间:2023-10-16

这是我的powmod函数:

int powmod(int b, int e, int m)
{
    int result = 1;
    while(e > 0){
        if(e & 1){
            result *= b;
            result %= m;
        }
        b *= b;
        b %= m;
        e >>= 1;
    }
    return result;
}

所以当我使用这个函数时,我只需要插入:

powmod(2,6,11);

就是2^6 mod 11,如果我想插入(2^6*11)mod p。我应该如何修改或插入值?

不等于:

powmod(2,6,11) * (11%p); //the result is different from (2^6*11) mod p

如果您指的是(2^(6*11)) mod p,则应该插入调用powmod(2, 6 * 11, p)的结果

如果您指的是((2^6) * 11) mod p,您可以执行以下操作

long long int a = powmod(2, 6, p);
a *= 11 % p;  /* mod -> % */
a %= p;

(int)a包含您需要的值,所以插入它。

作为旁注,函数中的int值可能溢出。

应该用更宽的int捕获乘法结果,或者编写一个不会溢出的自定义乘法函数。

IDEA1

int powmod(int b_, int e, int m)
{
    long long int result = 1LL;
    long long int b = b_;
    while(e > 0){
        if(e & 1){
            result *= b;
            result %= m;
        }
        b *= b;
        b %= m;
        e >>= 1;
    }
    return (int)result;
}

IDEA2

int safe_mul(int m1, int m2, int modulus) {
  /* Useful for competetions where modulus is usually 10^9 + 7 or 10^9 + 9 */
  /* If modulus is larger, this would need more modifications while adding */
  int i = 0, j = m1;
  while(m2) {
    if(m2 % 2) i = (i + j) % modulus;
    j = (2 * j) % modulus;
    m2 /= 2;
  }
  return i % modulus;
}
int powmod(int b, int e, int m)
{
    int result = 1;
    while(e > 0){
        if(e & 1){
            result = safe_mul(result, b, p);
            result %= m;
        }
        b = safe_mul(b, b, p);
        e >>= 1;
    }
    return result;
}

这两个想法都只是给你一个如何实现功能的想法。

Mohit Jain通过减少泛化调用正确地回答了这个问题,这将是:

int val = powmod( powmod(2,6,11)*11, 1, 11 );

但是我只想指出x * y (mod y),总是零。所以事实上,你的例子简化为:

int val = 0;