結果

問題 No.109 N! mod M
ユーザー 古寺いろは古寺いろは
提出日時 2015-04-08 22:48:17
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 110 ms / 5,000 ms
コード長 907 bytes
コンパイル時間 1,200 ms
コンパイル使用メモリ 144,604 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:24:34
合計ジャッジ時間 1,999 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include "bits/stdc++.h"
using namespace std;

bool isPrime(long long N){
	for (int i = 2; i * i <= N; i++)
	{
		if (N % i == 0) return false;
	}
	return true;
}

long long powmod(long long a, int p, long long M){
	if (p == 0) return 1;
	if (p % 2 == 1){
		return a * powmod(a, p - 1, M) % M;
	}
	else{
		long long c = powmod(a, p / 2, M);
		return c * c % M;
	}
}

long long calc(int N, int M){
	if (N >= M) return 0;
	if (N <= 100005){
		long long ret = 1 % M;
		for (int i = 1; i <= N; i++)
		{
			ret *= i;
			ret %= M;
		}
		return ret;
	}
	else{
		if (!isPrime(M)) return 0;
		long long ret = M - 1;
		long long div = 1;
		for (int i = M - 1; i > N; i--)
		{
			div *= i;
			div %= M;
		}
		div = powmod(div, M - 2, M);
		ret *= div;
		ret %= M;
		return ret;
	}
}

int main(){
	int T;
	cin >> T;
	while (T > 0){
		T--;
		long long N, M;
		cin >> N >> M;
		cout << calc(N, M) << endl;
	}
	cin >> T;
}
0