結果

問題 No.109 N! mod M
ユーザー hotpepsihotpepsi
提出日時 2014-12-22 01:12:52
言語 Python2
(2.7.18)
結果
WA  
実行時間 -
コード長 855 bytes
コンパイル時間 80 ms
コンパイル使用メモリ 6,516 KB
実行使用メモリ 13,788 KB
最終ジャッジ日時 2023-09-02 21:21:07
合計ジャッジ時間 7,955 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 31 ms
6,036 KB
testcase_01 AC 361 ms
13,364 KB
testcase_02 AC 455 ms
11,996 KB
testcase_03 AC 30 ms
6,120 KB
testcase_04 WA -
testcase_05 TLE -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

primes = [2]

def isprime(n):
  for p in primes:
    if p * p > n:
      return 1
    if (n % p) == 0:
      return 0
  return 1

def extgcd(a, b, x, y):
  d = a
  if b != 0:
    (d, x, y) = extgcd(b, a % b, y, x)
    y -= (a / b) * x
  else:
    x = 1
    y = 0
  return (d, x, y)

def modinv(a, m):
  (d, x, y) = extgcd(a, m, 1, 0)
  if d == 1:
    return (x + m) % m
  return 0

def solve(N, M):
  r = 1
  if M < N:
    return 0
  if M <= 200000:
    for n in range(2, N+1):
      r = (r * n) % M
    return r
  if not isprime(M):
    return 0
  r = M - 1
  for n in range(N+1, M):
    r = (r * modinv(n, M)) % M
  return r

n = 3
while n < 32000:
  if isprime(n):
    primes.append(n)
  n += 2

T = int(sys.stdin.readline())
for t in range(T):
  (N, M) = [int(x) for x in sys.stdin.readline().rstrip("\n").split(" ")]
  print(solve(N, M))
0