首页 > 解决方案 > 计算 a^b^c mod 10^9+7

问题描述

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

输入 -

1
7
8
10

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

我的代码 -

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

标签: c++exponentiationmodular

解决方案


您的解决方案基于不正确的数学假设。如果你想计算 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 ,因为费马小定理有效。因此,您需要在不同的模数下计算指数 b c 。


推荐阅读