Розбір
Since the number is prime, by Fermat's Little Theorem, the equality holds for any where . This equality can be rewritten as , which implies that the multiplicative inverse of is . Consequently, .
The multiplicative inverse can also be found using the extended Euclidean algorithm. To do this, one needs to solve the congruence . Consider the Diophantine equation
and find its particular solution using the extended Euclidean algorithm. Taking the equation modulo , we get . If is negative, should be added to it. Thus, is the multiplicative inverse of .
Example
Let’s consider the second sample. We need to compute . To do this, we should solve the equation , from which it follows that .
Since the number is prime, by Fermat's Little Theorem, it follows that or . Therefore, .
Compute the answer: .
Algorithm realization
The function powmod computes the value of .
long long powmod(long long x, long long n, long long m) { if (n == 0) return 1; if (n % 2 == 0) return powmod((x * x) % m, n / 2, m); return (x * powmod(x, n - 1, m)) % m; }
The main part of the program. Read the input data.
scanf("%lld %lld %lld", &a, &b, &n);
Calculate the values .
y = powmod(b, n - 2, n); x = (a * y) % n;
Print the answer.
printf("%lld\n", x);
Algorithm realization — the Extended Euclidean algorithm
#include <stdio.h> long long a, b, n, d, x, y, inv, res; void gcdext(long long a, long long b, long long &d, long long &x, long long &y) { if (b == 0) { d = a; x = 1; y = 0; return; } gcdext(b, a % b, d, x, y); long long s = y; y = x - (a / b) * y; x = s; } int main(void) { scanf("%lld %lld %lld", &a, &b, &n); // b * inv + n * y = 1 gcdext(b, n, d, inv, y); if (inv < 0) inv += n; res = (a * inv) % n; printf("%lld\n", res); return 0; }
Python realization
The main part of the program. Read the input data.
a, b, n = map(int, input().split())
Calculate the values .
y = pow(b, n - 2, n) x = (a * y) % n
Print the answer.
print(x)