結果

問題 No.109 N! mod M
ユーザー ぴろずぴろず
提出日時 2015-03-06 16:57:30
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,933 bytes
コンパイル時間 2,062 ms
コンパイル使用メモリ 75,652 KB
実行使用メモリ 56,432 KB
最終ジャッジ日時 2023-09-06 15:30:12
合計ジャッジ時間 4,766 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 150 ms
55,740 KB
testcase_01 WA -
testcase_02 AC 268 ms
56,260 KB
testcase_03 WA -
testcase_04 AC 196 ms
56,408 KB
testcase_05 AC 268 ms
56,432 KB
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

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 = 1;
			}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);
		}
	}

	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;
	}

}
0