結果
| 問題 |
No.109 N! mod M
|
| ユーザー |
|
| 提出日時 | 2017-08-14 00:05:33 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 104 ms / 5,000 ms |
| コード長 | 2,174 bytes |
| コンパイル時間 | 1,427 ms |
| コンパイル使用メモリ | 167,472 KB |
| 実行使用メモリ | 5,248 KB |
| 最終ジャッジ日時 | 2024-10-13 09:23:52 |
| 合計ジャッジ時間 | 2,121 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 9 |
ソースコード
// {{{ Templates
#include <bits/stdc++.h>
#define show(x) cerr << #x << " = " << x << endl
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
os << "sz:" << v.size() << "\n[";
for (const auto& p : v) {
os << p << ",";
}
os << "]\n";
return os;
}
template <typename S, typename T>
ostream& operator<<(ostream& os, const pair<S, T>& p)
{
os << "(" << p.first << "," << p.second
<< ")";
return os;
}
constexpr ll MOD = (ll)1e9 + 7LL;
template <typename T>
constexpr T INF = numeric_limits<T>::max() / 100;
// }}}
template <typename T>
T extgcd(const T a, const T b, T& x, T& y) // ax+by=gcd(a,b)
{
T d = a;
if (b != 0) {
d = extgcd(b, a % b, y, x);
y -= (a / b) * x;
} else {
x = 1;
y = 0;
}
return d;
}
inline bool isprime(const ll n)
{
for (ll i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
constexpr ll LIMIT = 100000;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int T;
cin >> T;
for (int t = 0; t < T; t++) {
ll N, M;
cin >> N >> M;
if (N == 0) {
cout << 1 % M << endl;
continue;
}
if (N >= M) {
cout << 0 << endl;
continue;
}
if (N <= LIMIT) {
ll prod = 1;
for (ll i = 1; i <= N; i++) {
prod = (prod * i) % M;
}
cout << prod << endl;
} else {
if (not isprime(M)) {
cout << 0 << endl;
} else {
ll prod = 1;
for (ll i = N + 1; i <= M - 1; i++) {
prod = (prod * i) % M;
}
ll inv = 0;
ll tmp = 0;
extgcd(prod, M, inv, tmp);
inv = ((inv % M) + M) % M;
assert((inv * prod) % M == 1);
cout << (inv * (M - 1)) % M << endl;
}
}
}
return 0;
}