結果
問題 |
No.109 N! mod M
|
ユーザー |
![]() |
提出日時 | 2018-01-15 16:38:24 |
言語 | Java (openjdk 23) |
結果 |
WA
|
実行時間 | - |
コード長 | 2,536 bytes |
コンパイル時間 | 2,959 ms |
コンパイル使用メモリ | 77,968 KB |
実行使用メモリ | 86,464 KB |
最終ジャッジ日時 | 2024-12-24 02:38:46 |
合計ジャッジ時間 | 10,974 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 6 WA * 2 TLE * 1 |
ソースコード
import java.io.*; import java.util.*; import java.math.BigInteger; class Main { static long powerMod(long x, long exponent, long MOD) { long prod = 1; for (int i = 63; i >= 0; --i) { prod = (prod * prod) % MOD; if ((exponent & 1L << i) != 0) { prod = (prod * x) % MOD; } } return prod; } static long f(long n,long m){ if(n>=m)return 0; if(m>=2*n){ // brute long ans=1; for(long i=1;i<=n;++i)ans=ans*i%m; return ans; } boolean pr=BigInteger.valueOf(m).isProbablePrime(20); if(pr){ // Wilson's theorem long ans=m-1; for(long i=m-1;i>n;--i){ ans=ans*powerMod(i,m-2,m)%m; } return ans; } return 0; } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t=sc.nextInt(); while(t-->0){ long n=sc.nextLong(); long m=sc.nextLong(); out.println(f(n,m)); } out.close(); } // http://codeforces.com/blog/entry/7018 //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n){ int[]r=new int[n]; for(int i=0;i<n;++i)r[i]=nextInt(); return r; } } }