P5431 【模板】模意义下的乘法逆元 2
题目描述
给定 个正整数 ,求它们在模 意义下的乘法逆元。
由于输出太多不好,所以将会给定常数 ,你要输出的答案为:
答案对 取模。
输入格式
第一行三个正整数 ,意义如题目描述。 第二行 个正整数 ,是你要求逆元的数。
输出格式
输出一行一个整数,表示答案。
输入输出样例 #1
输入 #1
6 233 42
1 4 2 8 5 7输出 #1
91说明/提示
对于 的数据,。
对于 数据,,,,保证 为质数。
提示:本题时间限制较为严格,请注意使用较快的 IO 方式。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const int N = 5010000;
int n, p, k, a[N];
ll s[N], inv[N];
int read() {
int k = 0, f = 1;
char c = getchar_unlocked();
while(c < '0' || c > '9') {
if(c == '-') f *= -1;
c = getchar_unlocked();
}
while('0' <= c && c <= '9') k = k * 10 + (c - '0'), c = getchar_unlocked();
return f * k;
}
void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x < 10) putchar(x + '0');
else write(x / 10), putchar(x % 10 + '0');
}
int exgcd(int a, int b, int &x, int &y) { // 返回值是 (a, b)
if (b == 0) {
x = 1;
y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y -= (a / b) * x;
return d;
}
int main() {
n = read(); p = read(); k = read();
for (int i = 1; i <= n; i ++) a[i] = read();
s[0] = 1;
for (int i = 1; i <= n; i++) s[i] = s[i - 1] * a[i] % p;
int x, y;
exgcd(s[n], p, x, y);
if (x < 0) x += p;
inv[n] = x;
for (int i = n; i; i--) inv[i - 1] = inv[i] * a[i] % p;
ll ans = 0, q = 1;
for (int i = 1; i <= n; i++) {
q = q * k % p;
ll ans2 = s[i - 1] * inv[i] % p;
ans = (ans + ans2 * q) % p;
}
write(ans);
return 0;
}