結果
| 問題 | No.109 N! mod M |
| コンテスト | |
| ユーザー |
夕叢霧香(ゆうむらきりか)
|
| 提出日時 | 2018-01-15 16:45:58 |
| 言語 | Java (openjdk 23) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,544 bytes |
| 記録 | |
| コンパイル時間 | 3,835 ms |
| コンパイル使用メモリ | 77,776 KB |
| 実行使用メモリ | 43,316 KB |
| 最終ジャッジ日時 | 2024-12-24 02:39:58 |
| 合計ジャッジ時間 | 4,583 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 8 WA * 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==4||2*m>=3*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*i%m;
}
return powerMod(ans,m-2,m);
}
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;
}
}
}
夕叢霧香(ゆうむらきりか)