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;  
}

  

相关文章:

  • 2021-12-05
  • 2021-12-14
猜你喜欢
  • 2021-09-08
  • 2021-12-30
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2021-04-20
  • 2022-12-23
相关资源
相似解决方案