【问题标题】:Modular exponentiation of a fraction分数的模幂
【发布时间】:2020-04-03 06:12:48
【问题描述】:

有理数的模,即 a/b,其中 a,b 属于整数集,可以通过计算 b.mod(m) = b-1 的模逆来找到。最后 a*b-1mod(m) 给了我们所需的结果。 我们如何有效地找到 (a/b)n 的模?给定 n 的数量级为 1e9,是否有一种有效的方法来计算结果,同时牢记值的溢出? 我尝试了以下类似的方法。

const int modular = 1e9+7;


int modular_inverse(long long base) {
    long long result = 1;
    int power = modular-2;
    int MOD = modular;
    while(power > 0) {

        if(power & 1) {
            result = (result*base) % MOD;
        }
        base = (base * base) % MOD;
        power >>= 1;
    }
    return result;
}

int main() {
    int a = 27;
    int b = 2048;
    int A = a;
    int B = b;

    for(int i = 0; i < 1e9-1; ++i) {
        A *= a;
        B *= b;
        A = A%modular;
        B = B%modular;
    }
    int B_inv = modular_inverse(B);
    long long res = A*B_inv;
    res = res%mod;
    cout << res << endl;
}

【问题讨论】:

  • 关于问题发布说明:使用 上标表达式 表示要在上标中提出的术语。

标签: c++ modular


【解决方案1】:

您可以使用fast exponentiation

计算 (ab-1)nmod(M)

请注意,您实际上在 modular_inverse 函数中实现了快速求幂,在该函数中计算 base-1mod(M) 等于 baseM- 2mod(M) 如果 M 是素数。

所以你需要计算 b-1(你已经做了),然后计算 (ab-1)mod(M) .然后使用快速取幂将结果提高到 n 次方,对 M 进行所有运算。

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 2018-01-15
    • 2014-08-21
    • 2017-04-03
    • 2015-06-13
    • 2020-05-14
    • 2014-07-19
    相关资源
    最近更新 更多