結果
| 問題 | No.109 N! mod M |
| コンテスト | |
| ユーザー |
mayoko_
|
| 提出日時 | 2014-12-22 12:51:02 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
AC
|
| 実行時間 | 1,351 ms / 5,000 ms |
| コード長 | 1,429 bytes |
| コンパイル時間 | 600 ms |
| コンパイル使用メモリ | 74,440 KB |
| 実行使用メモリ | 6,944 KB |
| 最終ジャッジ日時 | 2024-06-22 04:48:49 |
| 合計ジャッジ時間 | 2,634 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 9 |
ソースコード
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#define INF 1000000000
using namespace std;
typedef long long ll;
bool isPrime(ll n) {
for (ll i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
// extgcd
ll extgcd(ll a, ll b, ll& x, ll& y) {
ll d = a;
if (b != 0) {
d = extgcd(b, a % b, y, x);
y -= (a / b) * x;
} else {
x = 1; y = 0;
}
return d;
}
// mod_inverse
ll mod_inverse(ll a, ll m) {
ll x, y;
extgcd(a, m, x, y);
return (m+x%m) % m;
}
int main(void) {
int T;
cin >> T;
while (T--) {
int N, M;
cin >> N >> M;
if (N >= M) {
cout << 0 << endl;
continue;
}
if (M <= 2*100000) {
ll ans = 1;
for (ll i = 1; i <= N; i++) {
ans = (ans*i) % M;
}
cout << ans % M << endl;
continue;
}
if (!isPrime(M)) {
cout << 0 << endl;
} else {
ll ans = M-1;
for (ll i = N+1; i <= M-1; i++) {
ans = (ans * mod_inverse(i, M)) % M;
}
cout << ans << endl;
}
}
return 0;
}
mayoko_