結果

問題 No.109 N! mod M
ユーザー pekempeypekempey
提出日時 2015-09-04 16:15:31
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 110 ms / 5,000 ms
コード長 1,093 bytes
コンパイル時間 1,139 ms
コンパイル使用メモリ 144,932 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:26:52
合計ジャッジ時間 2,114 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 76 ms
4,376 KB
testcase_02 AC 101 ms
4,380 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 4 ms
4,380 KB
testcase_05 AC 110 ms
4,380 KB
testcase_06 AC 13 ms
4,380 KB
testcase_07 AC 15 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i, a) for (int i = 0; i < (a); i++)
#define rep2(i, a, b) for (int i = (a); i < (b); i++)
#define repr(i, a) for (int i = (a) - 1; i >= 0; i--)
#define repr2(i, a, b) for (int i = (b) - 1; i >= (a); i--)
using namespace std;
typedef long long ll;

ll modpow(ll a, ll b, ll mod) {
	if (b == 0) return 1;
	return modpow(a * a % mod, b / 2, mod) * (b & 1 ? a : 1) % mod;
}

ll modinv(ll a, ll mod) {
	return modpow(a, mod - 2, mod);
}

bool isprime(ll n) {
	for (ll i = 2; i * i <= n; i++) {
		if (n % i == 0) return false;
	}
	return n != 1;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		ll N, M;
		cin >> N >> M;
		if (N >= M) {
			cout << 0 << endl;
		} else if (isprime(M)) {
			ll fact = M - 1;
			ll prod = 1;
			for (ll i = N + 1; i < M; i++) {
				prod *= i;
				prod %= M;
			}
			fact *= modinv(prod, M);
			fact %= M;
			cout << fact << endl;
		} else {
			if (M <= 1000000) {
				ll fact = 1 % M;
				rep (i, N) {
					fact *= i + 1;
					fact %= M;
				}
				cout << fact << endl;
			} else {
				cout << 0 << endl;
			}
		}
	}
	return 0;
}
0