繁体   English   中英

计算 a^b^c mod 10^9+7

[英]Calculating a^b^c mod 10^9+7

问题链接 - https://cses.fi/problemset/task/1712

输入 -

1
7
8
10
  • 预计 Output - 928742408
  • 我的 output - 989820350

让我感到困惑的一点 - 在 100 多个输入中,仅在 1 或 2 个测试用例中,我的代码提供了错误的 output,如果代码错误,它不应该为所有内容提供错误的 output 吗?

我的代码 -

#include <iostream>
#include <algorithm>

typedef unsigned long long ull;
constexpr auto N = 1000000007;

using namespace std;

ull binpow(ull base, ull pwr) {
    base %= N;
    ull res = 1;
    while (pwr > 0) {
        if (pwr & 1)
            res = res * base % N;
        base = base * base % N;
        pwr >>= 1;
    }
    return res;
}

ull meth(ull a, ull b, ull c) {
    if (a == 0 && (b == 0 || c == 0))
        return 1;
    if (b == 0 && c == 0)
        return 1;
    if (c == 0)
        return a;

    ull pwr = binpow(b, c);
    ull result = binpow(a, pwr);

    return result;
}

int main() {

    ios_base::sync_with_stdio(0);
    cin.tie(0);
    ull a, b, c, n;
    cin >> n;

    for (ull i = 0; i < n; i++) {
        cin >> a >> b >> c;
        cout << meth(a, b, c) << "\n";
    }
    return 0;
}
`

您的解决方案基于不正确的数学假设。 如果你想计算 a b c mod m 你不能减少指数 b c mod 10 9 + 7。换句话说,a b c mod m != a b c mod m mod m。 相反,您可以将它减少 mod 10 9 + 6 ,因为Fermat's little theorem 因此,您需要计算不同模数下的指数 b c

以供参考


改变

ull pwr = binpow(b, c);

以a pwr = b c计算。

8 10 --> 1,073,741,824

7 1,073,741,824 mod 100000007 --> 928742408


如果代码错误,它不应该为所有内容提供错误的 output 吗?

可能其他 b c总是 < 100000007

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM