結果
| 問題 | No.109 N! mod M |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2017-08-13 23:49:02 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.89.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,994 bytes |
| 記録 | |
| コンパイル時間 | 1,554 ms |
| コンパイル使用メモリ | 168,904 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-10-13 09:23:38 |
| 合計ジャッジ時間 | 2,157 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 4 WA * 5 |
ソースコード
// {{{ 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 >= 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 = 1; i <= M - N - 1; i++) {
prod = (prod * i) % M;
}
ll inv = 0;
ll tmp = 0;
extgcd(prod, M, inv, tmp);
cout << (inv * (M - 1)) % M << endl;
}
}
}
return 0;
}