CSES - Aalto Competitive Programming 2024 - wk11 - Homework - Results
Submission details
Task:Finding inverse
Sender:esya_rae
Submission time:2024-11-18 12:31:44 +0200
Language:C++ (C++17)
Status:READY
Result:
Test results
testverdicttime
#1ACCEPTED0.00 sdetails
#2ACCEPTED0.00 sdetails
#3ACCEPTED0.00 sdetails
#4ACCEPTED0.00 sdetails
#5ACCEPTED0.00 sdetails
#6ACCEPTED0.00 sdetails
#7ACCEPTED0.00 sdetails
#8ACCEPTED0.00 sdetails
#9--details
#10--details
#11--details
#12--details
#13--details
#14--details

Code

#include <iostream>
#include <vector>
using namespace std;
#define int long long

vector<int> sieve_primes(int n) {
    vector<int> primes = {2};
    for (int i = 3; i <= n / 2; i += 2) {
        bool is_prime = true;
        for (int p : primes) {
            if (i % p == 0) {
                is_prime = false;
                break;
            }
        }
        if (is_prime) {
            primes.push_back(i);
        }
    }
    return primes;
}

int euler(int n, const vector<int>& primes) {
    vector<int> div;
    for (int p : primes) {
        if (n % p == 0) {
            div.push_back(p);
        }
    }
    if (div.empty()) {
        return n - 1;
    }
    int c = n;
    for (int d : div) {
        c *= (d - 1);
        c /= d;
    }
    return c;
}

int fast_exp(int a, int b, int mod) {
    if (b == 0) {
        return 1;
    }
    int g = 1;
    while (b > 1) {
        if (b % 2 == 1) {
            g = (g * a) % mod;
            b--;
        }
        a = (a * a) % mod;
        b /= 2;
    }
    return (a * g) % mod;
}

signed main() {
    int a, M;
    cin >> a >> M;

    vector<int> primes = sieve_primes(M);
    int e = euler(M, primes);

    int r = fast_exp(a, e - 1, M);

    if ((r * a) % M == 1) {
        cout << r << endl;
    } else {
        cout << -1 << endl;
    }

    return 0;
}

Test details

Test 1

Verdict: ACCEPTED

input
6 7

correct output
6

user output
6

Test 2

Verdict: ACCEPTED

input
0 7

correct output
-1

user output
-1

Test 3

Verdict: ACCEPTED

input
5 78

correct output
47

user output
47

Test 4

Verdict: ACCEPTED

input
89 99

correct output
89

user output
89

Test 5

Verdict: ACCEPTED

input
0 61

correct output
-1

user output
-1

Test 6

Verdict: ACCEPTED

input
897 947

correct output
625

user output
625

Test 7

Verdict: ACCEPTED

input
419 538

correct output
217

user output
217

Test 8

Verdict: ACCEPTED

input
32 938

correct output
-1

user output
-1

Test 9

Verdict:

input
184120 505187

correct output
438779

user output
(empty)

Test 10

Verdict:

input
264601 885661

correct output
360221

user output
(empty)

Test 11

Verdict:

input
40310 590135

correct output
-1

user output
(empty)

Test 12

Verdict:

input
202254499 577081420

correct output
128866679

user output
(empty)

Test 13

Verdict:

input
539836073 888851205

correct output
797044652

user output
(empty)

Test 14

Verdict:

input
697847215 756971670

correct output
-1

user output
(empty)