結果

問題 No.109 N! mod M
ユーザー r_dream0r_dream0
提出日時 2017-02-09 00:57:03
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 1,138 ms / 5,000 ms
コード長 1,089 bytes
コンパイル時間 400 ms
コンパイル使用メモリ 59,564 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:37:57
合計ジャッジ時間 2,429 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 179 ms
4,380 KB
testcase_02 AC 98 ms
4,380 KB
testcase_03 AC 3 ms
4,380 KB
testcase_04 AC 17 ms
4,376 KB
testcase_05 AC 1,138 ms
4,380 KB
testcase_06 AC 23 ms
4,376 KB
testcase_07 AC 13 ms
4,376 KB
testcase_08 AC 4 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdint>
#include <vector>
using namespace std;
int64_t extgcd(long a, long b, long &x, long &y) {
  for (int64_t u = y = 1, v = x = 0; a; ) {
    int64_t q = b / a;
    swap(x -= q * u, u);
    swap(y -= q * v, v);
    swap(b -= q * a, a);
  }
  return b;
}

int64_t mod_inverse(long a, long mod) {
  int64_t x, y;
  extgcd(a, mod, x, y);
  x %= mod;
  if(x < 0) x+= mod;
  return x;
}

bool is_prime(int64_t N) {
  if(N == 1) return false;
  for(int64_t i = 2; i * i <= N; i++) {
    if(N % i == 0) return false;
  }
  return true;
}
int main() {
  int32_t T;
  cin >> T;
  while(T--) {
    int64_t N, M;
    cin >> N >> M;
    if(N <= 1000000) {
      int64_t r = 1;
      for(int64_t i = 1; i <= N; i++) {
        r = r * i % M;
      }
      cout << r % M << endl;
    } else if(!is_prime(M) || N >= M) {
      // Mが素数じゃない → 0
      cout << 0 << endl;
    }else{
      int64_t r = M - 1; // (M - 1)! = M - 1 % M
      for(int64_t i = M - 1; i > N; i--) {
        r = r * mod_inverse(i, M) % M;
      }
      cout << r << endl;
    }
  }
}
0