結果
問題 | No.109 N! mod M |
ユーザー | ぴろず |
提出日時 | 2015-03-06 17:04:57 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 256 ms / 5,000 ms |
コード長 | 1,937 bytes |
コンパイル時間 | 1,969 ms |
コンパイル使用メモリ | 79,492 KB |
実行使用メモリ | 55,020 KB |
最終ジャッジ日時 | 2024-06-22 04:50:16 |
合計ジャッジ時間 | 4,236 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 9 |
ソースコード
package no109a; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<Integer> primes = Sieve.primeList((int) Math.sqrt(1_000_000_000) + 2); Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int tt=0;tt<t;tt++) { int n = sc.nextInt(); int m = sc.nextInt(); long ans = 1; if (m <= n) { ans = 0; }else if (m <= 200000) { for(int i=1;i<=n;i++) { ans = ans * i % m; } }else{ if (Sieve.primeFactorL(primes, m).size() >= 2) { ans = 0; }else{ long div = 1; for(int i=n+1;i<=m-1;i++) { div = div * i % m; } ans = (m - 1) * modInv(div, m) % m; } } System.out.println(ans % m); } } public static long modpow(long x,long n,long mod) { long res = 1; while(n > 0) { if ((n & 1) > 0) { res = (res * x) % mod; } x = (x * x) % mod; n/=2; } return res; } public static long modInv(long x,long modP) { return modpow(x, modP-2, modP); } } class Sieve { public static boolean[] isPrimeArray(int max) { boolean[] isPrime = new boolean[max+1]; Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false; for(int i=2;i*i<=max;i++) { if (isPrime[i]) { int j = i * 2; while(j<=max) { isPrime[j] = false; j += i; } } } return isPrime; } public static ArrayList<Integer> primeList(int max) { boolean[] isPrime = isPrimeArray(max); ArrayList<Integer> primeList = new ArrayList<Integer>(); for(int i=2;i<=max;i++) { if (isPrime[i]) { primeList.add(i); } } return primeList; } public static ArrayList<Long> primeFactorL(ArrayList<Integer> primeList,long num) { ArrayList<Long> ret = new ArrayList<Long>(); for(int p:primeList) { while(num % p == 0) { num /= p; ret.add((long) p); } } if (num > 1) { ret.add(num); } return ret; } }