1

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;
}
`
Aziz
  • 17,407
  • 5
  • 59
  • 66
  • If I am not wrong, b^c must be canculated `mod N-1` and not `mod N`. The order of the multiplicity group of GF(N) is N-1 – Damien May 28 '20 at 04:43
  • "in only 1 or 2 test cases my code is providing wrong output," --> What is the other wrong output? – chux - Reinstate Monica May 28 '20 at 05:00
  • "if the code is wrong shouldn't it give wrong output for everything?" - Absolutely not. Wrong code outputs right results all the time. Just because it's wrong doesn't mean it always has to output the wrong result. – BessieTheCookie May 28 '20 at 05:09
  • The idea is that x^(N-1) = 1 mod N, if N is prime – Damien May 28 '20 at 06:11
  • [How to compute a^b^c mod p?](https://stackoverflow.com/q/46944581/995714), [How to evalute an exponential tower modulo a prime](https://stackoverflow.com/q/21367824/995714), [finding a^b^c^… mod m](https://stackoverflow.com/q/4223313/995714) – phuclv May 28 '20 at 06:14
  • @Damien, yes, it worked – Chitransh Saxena May 28 '20 at 06:30

2 Answers2

2

Your solution is based on an incorrect mathematical assumption. If you want to compute abc mod m you can't reduce the exponent bc mod 109+7. In other words, abc mod m != abc mod m mod m. Instead, you can reduce it mod the Euler totient function of 109+7, which is 109+6 because 109+7 is prime. This works because of Fermat's little theorem. Therefore, you need to compute your exponent bc under a different modulo.

BessieTheCookie
  • 4,571
  • 4
  • 13
  • 32
0

For reference


Change

ull pwr = binpow(b, c);

To a pwr = bc calculation.

810 --> ‭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 bc were always < 100000007

chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213