大数乘法取模

2020-02-22 23:18:45

问题描述

求解 (num1 * num2) % mod 的值,注意num1 * num2会溢出。

问题求解

最简单的想法就是遍历一遍,但是会超时!

int mul(int num1, int num2, int mod) {
    int res = 0;
    for (int i = 0; i < num2; i++) {
        res = (res + num1) % mod;
    }
    return res;    
}

使用快速取模就会快非常多!

int qmul(int num1, int num2, int mod) {
    int res = 0;
    while (num2 != 0) {
        if ((num2 & 1) != 0) {
            res = (res + num1) % mod;
        }
        res = res * 2 % mod;
        num2 >>= 1;
    }
    return res  
}

  

猜你喜欢

转载自www.cnblogs.com/hyserendipity/p/12348066.html
今日推荐