简体   繁体   中英

Calculating a^b^c mod 10^9+7

Problem Link - https://cses.fi/problemset/task/1712

input -

1
7
8
10
  • Expected Output - 928742408
  • My output - 989820350

point that is confusing me - Out of 100s of inputs, in only 1 or 2 test cases my code is providing wrong output, if the code is wrong shouldn't it give wrong output for everything?

My code -

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

Your solution is based on an incorrect mathematical assumption. If you want to compute a b c mod m you can't reduce the exponent b c mod 10 9 + 7. In other words, a b c mod m != a b c mod m mod m. Instead, you can reduce it mod 10 9 + 6 which works because of Fermat's little theorem . Therefore, you need to compute your exponent b c under a different modulus.

For reference


Change

ull pwr = binpow(b, c);

To a pwr = b c calculation.

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

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


if the code is wrong shouldn't it give wrong output for everything?

Likely the other b c were always < 100000007

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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