結果
| 問題 |
No.109 N! mod M
|
| ユーザー |
r_dream0
|
| 提出日時 | 2017-02-09 00:47:53 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,076 bytes |
| コンパイル時間 | 613 ms |
| コンパイル使用メモリ | 58,076 KB |
| 実行使用メモリ | 5,248 KB |
| 最終ジャッジ日時 | 2024-12-25 17:06:54 |
| 合計ジャッジ時間 | 2,551 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 8 WA * 1 |
ソースコード
#include <iostream>
#include <cstdint>
#include <vector>
using namespace std;
long extgcd(long a, long b, long &x, long &y) {
for (long u = y = 1, v = x = 0; a; ) {
long q = b / a;
swap(x -= q * u, u);
swap(y -= q * v, v);
swap(b -= q * a, a);
}
return b;
}
long mod_inverse(long a, long mod) {
long x, y;
extgcd(a, mod, x, y);
x %= mod;
if(x < 0) x+= mod;
return x;
}
bool is_prime(int64_t N) {
if(N == 1) return false;
for(int64_t i = 2; i * i <= N; i++) {
if(N % i == 0) return false;
}
return true;
}
int main() {
int32_t T;
cin >> T;
while(T--) {
int64_t N, M;
cin >> N >> M;
if(N <= 1000000) {
int64_t r = 1;
for(int64_t i = 1; i <= N; i++) {
r = r * i % M;
}
cout << r << endl;
} else {
// Mが素数じゃない → 0
if(!is_prime(M) || N >= M) {
cout << 0 << endl;
}else{
int64_t r = M - 1;
for(int64_t i = M - 1; i > N; i--) {
r = r * mod_inverse(i, M) % M;
}
cout << r << endl;
}
}
}
}
r_dream0