結果

問題 No.109 N! mod M
ユーザー r_dream0
提出日時 2017-02-09 00:57:03
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 1,113 ms / 5,000 ms
コード長 1,089 bytes
コンパイル時間 668 ms
コンパイル使用メモリ 59,652 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-06-22 05:03:48
合計ジャッジ時間 2,556 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 9
権限があれば一括ダウンロードができます

ソースコード

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