代码之家  ›  专栏  ›  技术社区  ›  Isaiah

如何有效地验证pow(a,b)%b==C中的a(无溢出)

  •  3
  • Isaiah  · 技术社区  · 7 年前

    在C中为true,其中2¥b¥32768(2 )和2?a?b,其中a和b为整数。

    然而,直接计算 pow(a, b) % b

    这个问题是基于费马小定理的证明,该定理指出,如果这个条件为假,b不是素数。

    b 这不是质数,但也不能满足 pow(a, b)% b == a 具有 2 <= a <= b pow(a, b) % b == a 具有 2 <= a <= 29341 不应该太慢。

    2 回复  |  直到 7 年前
        1
  •  5
  •   Mathieu Shrikanth M D    7 年前

    您可以使用 Exponentiation by squaring

    其思路如下:

    • b 以二进制形式并分解乘积
    • %b 低于32768,因此结果将始终适合32位数字。

    所以C代码是:

    /*
     * this function computes (num ** pow) % mod
     */
    int pow_mod(int num, int pow, int mod)
    {
        int res = 1
    
        while (pow>0)
        {
            if (pow & 1)
            {
                res = (res*num) % mod;
            }
            pow /= 2;
            num = (num*num)%mod;
        }
    
        return res;
    }
    
        2
  •  3
  •   Alexandre Fenyo    7 年前

    你在做Z/bZ中的模算术。

    (a^b) mod b = ((((a mod b) * a) mod b) * a) mod b [...] (b times)
    

    因此,您不需要一个大的整数库。

    您只需使用以下算法(伪代码)编写一个C程序:

    • 将变量a和b声明为整数。
    • 使用用a初始化的临时变量temp。
    • 用b步做一个循环,然后计算 (temp * a) mod b

    通过这个公式,可以看到temp的最高值是32768,因此可以选择一个 存储温度。