結果
| 問題 |
No.109 N! mod M
|
| ユーザー |
|
| 提出日時 | 2014-12-23 19:58:16 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 1,103 bytes |
| コンパイル時間 | 393 ms |
| コンパイル使用メモリ | 57,528 KB |
| 実行使用メモリ | 13,888 KB |
| 最終ジャッジ日時 | 2024-06-12 04:13:31 |
| 合計ジャッジ時間 | 6,890 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 4 TLE * 1 -- * 4 |
ソースコード
#include<iostream>
using namespace std;
int n, m;
void read() {
cin >> n >> m;
}
bool isPrime(int M) {
for (int i = 2; i * i <= M; ++i)
if (M % i == 0)
return false;
return true;
}
int modpow(int p, int nMul, int mod) {
if (nMul == 0) return 1;
int t = modpow(p, nMul / 2, mod);
return nMul & 1 ? 1LL * t * t % mod * p % mod : 1LL * t * t % mod;
}
// mod: 素数
int inv(int num, int mod) {
return modpow(num, mod - 2, mod);
}
void work() {
if (n >= m) {
cout << 0 << endl;
return;
}
if (isPrime(m)) {
int toInv = 1;
for (int i = m - 1; i > n; --i)
toInv = 1LL * toInv * i % m;
cout << 1LL * (m - 1) * inv(toInv, m) % m << endl;
}
else {
int ans = 1;
for (int i = 1; i <= n; ++i) {
ans = 1LL * ans * i % m;
if (ans == 0)
break;
}
cout << ans << endl;
}
}
int main() {
int cases;
cin >> cases;
for (int i = 0; i < cases; ++i) {
read();
work();
}
return 0;
}