利用模函数实现乘幂
Using modulo function to implement power with multiply
这是我的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;
相关文章:
- 在命名空间内部还是外部实现 c++ 函数?
- 如何在C++中实现函数(f)(x)(y, z)(g)(r)
- 如何在C++中实现函数上的二叉搜索?
- 键按下事件错误 Qt 实现函数时
- 在子类之外实现函数导致未知错误
- 通过模板滥用实现函数式C++
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 我正在尝试创建自己的 strcat() 函数,而不是使用库实现函数<cstring>
- 如果未实现函数,则在链接时启用错误
- 用函数参数实现c++函数指针
- 如何在Android SDK中调用和实现C++函数
- 在 C++ RCPP 中实现 R 函数
- 实现函数模板填充多维对象
- 类的层次结构,试图在基本级别实现函数
- 用c++实现函数对象的自动检测类型
- 用shared_ptrs实现函数模板的C++实例化
- 在类中实现函数导致错误:成员引用基类型'ifstream (string)'不是结构或联合
- 用c++实现S函数.生成错误
- 引用可以用于实现函数重写吗
- 如何在c++中实现函数超时