結果

問題 No.109 N! mod M
ユーザー 👑 colognecologne
提出日時 2022-02-02 17:11:52
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 880 bytes
コンパイル時間 2,380 ms
コンパイル使用メモリ 86,752 KB
実行使用メモリ 76,328 KB
最終ジャッジ日時 2023-09-02 02:51:50
合計ジャッジ時間 2,637 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 71 ms
75,388 KB
testcase_01 AC 161 ms
75,480 KB
testcase_02 AC 181 ms
75,192 KB
testcase_03 AC 69 ms
71,168 KB
testcase_04 AC 76 ms
75,772 KB
testcase_05 AC 213 ms
76,328 KB
testcase_06 AC 92 ms
76,088 KB
testcase_07 WA -
testcase_08 AC 70 ms
75,580 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import itertools
import sys


def input(): return sys.stdin.readline().rstrip()


def isPrime(N):
    for i in itertools.count(2):
        if i*i > N:
            return True
        if N % i == 0:
            return False


def fact(N, M):
    # M - N <= LIM
    LIM = 10**5

    if N >= M:
        # trivial case
        return 0
    if M <= 2*LIM:
        # small case
        a = 1
        for i in range(1, N+1):
            a = a * i % M
        return a
    elif isPrime(M):
        # prime case, (M-1)! == -1 (mod M)
        a = M-1
        for i in range(N+1, M):
            a = a * i % M
        return pow(a, -1, M)
    else:
        # M = pq, q <= M/p <= M/2 <= M/2 + (M/2 - LIM) <= N
        return 0


def main():
    T = int(input())
    for i in range(T):
        N, M = map(int, input().split())
        print(fact(N, M))


if __name__ == '__main__':
    main()
0