結果

問題 No.109 N! mod M
ユーザー maspymaspy
提出日時 2020-04-02 23:42:57
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
WA  
実行時間 -
コード長 1,513 bytes
コンパイル時間 86 ms
コンパイル使用メモリ 11,056 KB
実行使用メモリ 35,620 KB
最終ジャッジ日時 2023-09-11 00:54:07
合計ジャッジ時間 3,116 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 144 ms
29,788 KB
testcase_01 AC 409 ms
35,620 KB
testcase_02 AC 502 ms
35,536 KB
testcase_03 AC 133 ms
29,596 KB
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 172 ms
34,968 KB
testcase_08 AC 136 ms
29,684 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 % M
    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, P)[-1]


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