結果

問題 No.109 N! mod M
ユーザー pluto77pluto77
提出日時 2016-12-26 10:55:40
言語 Python2
(2.7.18)
結果
AC  
実行時間 796 ms / 5,000 ms
コード長 694 bytes
コンパイル時間 468 ms
コンパイル使用メモリ 6,736 KB
実行使用メモリ 6,960 KB
最終ジャッジ日時 2023-09-04 05:37:15
合計ジャッジ時間 3,392 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 14 ms
5,864 KB
testcase_01 AC 549 ms
5,956 KB
testcase_02 AC 698 ms
6,052 KB
testcase_03 AC 12 ms
5,932 KB
testcase_04 AC 48 ms
6,916 KB
testcase_05 AC 796 ms
6,856 KB
testcase_06 AC 44 ms
6,960 KB
testcase_07 AC 83 ms
5,944 KB
testcase_08 AC 13 ms
6,824 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#yuki_109

def isPrime(n):
 if n==2 or n==3: return True
 if n%2==0 or n<2: return False
 for i in range(3,int(n**0.5)+1,2):
  if n%i==0:
   return False    
 return True

def egcd(a, b):
 if a==0:
  return (b,0,1)
 else:
  g,y,x=egcd(b % a, a)
  return (g,x-(b/a)*y,y)

def modinv(a,m):
 g,x,y=egcd(a, m)
 if not g==1:
  raise Exception('modular inverse does not exist')
 else:
  return x%m

t=int(raw_input())

for i in range(t):
 n,m=map(int,raw_input().split())
 if n>=m or m<=1:
  print 0
  continue
 if n<=300000:
  a=1
  for j in xrange(1,n+1):
   a=(a*j)%m;
  print a
  continue
 if isPrime(m)==False:
  print 0
  continue
 r=m-1
 for i in xrange(n+1,m):
  r=(r*i)%m
 print modinv(r,m)
0