乘方取模计算(模幂计算)

乘方取模计算也称为模幂计算,在密码系统中经常使用,是不可缺少的。

使用本程序可以解HDU2035,只需要考虑输入和输出。

/*
 * 乘方取模
 *
 * 已知给定的正整数a、n和m,计算x的值,a^n = x (mod m)。
 *
 * 二分法用在这里也很有效果。
 */

#include <stdio.h>

long powermod(long a, long n, long m)
{
    long res = 1L;
    while(n) {
        if(n & 1L) {
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        n >>= 1;
    }
    return res;
}

int main(void)
{
    printf("a=%ld, n=%ld, m=%ld, x=%ld
", 7L, 3L, 41L, powermod(7L, 3L, 41L));

    return 0;
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564973.html