結果

問題 No.109 N! mod M
ユーザー maspymaspy
提出日時 2020-04-02 23:40:45
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
RE  
実行時間 -
コード長 1,506 bytes
コンパイル時間 86 ms
コンパイル使用メモリ 10,968 KB
実行使用メモリ 35,644 KB
最終ジャッジ日時 2023-09-11 00:53:56
合計ジャッジ時間 5,132 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 143 ms
29,800 KB
testcase_01 AC 403 ms
35,644 KB
testcase_02 AC 497 ms
35,504 KB
testcase_03 AC 134 ms
29,608 KB
testcase_04 RE -
testcase_05 RE -
testcase_06 RE -
testcase_07 WA -
testcase_08 AC 131 ms
29,636 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/ python3.8
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np

T = int(readline())


def MillerRabinTest(n, maxiter=20):
    import random
    if n == 1:
        return False
    elif n == 2:
        return True
    if not n & 1:
        return False
    d = n - 1
    while not (d & 1):
        d >>= 1

    for _ in range(maxiter):
        a = random.randint(1, n - 1)
        t = d
        x = pow(a, t, n)
        while (t != n - 1) and (x != 1) and (x != n - 1):
            x = x * x % n
            t <<= 1
        if (x != n - 1) and not (t & 1):
            return False
    return True


def cumprod(A, MOD):
    L = len(A)
    Lsq = int(L**.5 + 1)
    A = np.resize(A, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        A[:, n] *= A[:, n - 1]
        A[:, n] %= MOD
    for n in range(1, Lsq):
        A[n] *= A[n - 1, -1]
        A[n] %= MOD
    return A.ravel()[:L]


def solve():
    N, M = map(int, readline().split())
    if N == 0:
        return 1
    if M <= 2 * 10 ** 5 + 10:
        if N >= M:
            return 0
        else:
            x = np.arange(1, N + 1, dtype=np.int64)
            return cumprod(x, M)[-1]
    if not MillerRabinTest(M):
        return 0
    # P is prime
    P = M
    if N >= P:
        return 0
    if N == P - 1:
        return P - 1
    x = np.arange(1, P - N, dtype=np.int64)
    return P - cumprod(x)[-1]


for _ in range(T):
    print(solve())
0