c++ - 模幂(模算术中的幂)

标签 c++ c algorithm math

Hello!
I am got stuck in understanding the concept of modular Exponentiation. When I need this and how this works.
Suppose I am calling the power function as : power(2,n-1).
How the loops will be executed for say n=10 and also the time and space complexity for the below problem

#define m 1000000007

unsigned long long int power(unsigned long long int x, unsigned long long int n){

    unsigned long long int res = 1;
    while(n > 0){
        if(n & 1){
            res = res * x;
            res = res % m;
        }
        x = x * x;
        x= x % m;
        n >>= 1;
    }
    return res;

}

最佳答案

从 Dale 链接的维基百科页面上的模法则(关于您之前的问题),我们可以获得两个公式:

enter image description here

从第一个公式可以清楚地看出,我们可以根据 n/2 的结果迭代计算 n 的模。这是由线条完成的

x = x * x;
x = x % m;

因此,算法中有 log n 个步骤,因为每次 x 的指数都会加倍。步数计数由 n >>= 1while (n > 0) 完成,计算 log n 步。

现在,您可能想知道 1) 为什么这部分不设置 res 的值,以及 2) 这些行的目的是什么

if(n & 1){
   res = res * x;
   res = res % m;
}

这是必要的,因为在迭代中的某些点,无论是开始还是结束,n 的值可能是奇数。我们不能忽略它并继续使用公式 1,因为这意味着我们将跳过 x 的幂! (整数除法向下舍入,例如 5 >> 1 = 2,我们将得到 x^4 而不是 x^5)。此 if 语句处理 n 为奇数的情况,即 n % 2 = n & 1 = 1。它只是使用上面的公式 2 将 x 的一次幂“添加”到结果中。

关于c++ - 模幂(模算术中的幂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566228/

相关文章:

c++ - 将 C 或 C++ 文件作为脚本运行

c++ - 如何在 C++ 中递归反转负整数?

c - 如何制作守护进程

c - 在支持 Windows XP 的 C 语言中获取和设置默认网关

algorithm - 为给定坐标的贝塞尔曲线找到合适的参数值

python - 第 k 个排列的第 i 个元素

java - 合并排序交换和比较

c++ - 直接从 C++ 使用 ZODB。示例和设计提示

c++ - Cocos2D-x App for BB Playbook/Z10 如何在 Facebook 状态分享分数?

C - 如何在方法中对数组进行排序和打印,但不影响先前未排序的数组