結果

問題 No.109 N! mod M
ユーザー r_dream0r_dream0
提出日時 2017-02-09 00:44:43
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,052 bytes
コンパイル時間 438 ms
コンパイル使用メモリ 58,980 KB
実行使用メモリ 4,504 KB
最終ジャッジ日時 2023-08-26 17:42:42
合計ジャッジ時間 1,466 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 WA -
testcase_02 AC 49 ms
4,376 KB
testcase_03 AC 3 ms
4,380 KB
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 AC 4 ms
4,376 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘long int mod_inverse(long int, long int)’:
main.cpp:17:5: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
   x %= mod;
   ~~^~~~~~

ソースコード

diff #

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

long mod_inverse(long a, long mod) {
  long 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 <= 100000) {
      int64_t r = 1;
      for(int64_t i = 1; i <= N; i++) {
        r = r * i % M;
      }
      cout << r << endl;
    } else {
      // Mが素数じゃない → 0
      if(!is_prime(M) || N >= M) {
        cout << 0 << endl;
      }else{
        int64_t r = M - 1;
        for(int64_t i = M - 1; i > N; i--) {
          r = r * mod_inverse(i, M) % M;
        }
        cout << r << endl;
      }
    }
  }
}
0