結果

問題 No.109 N! mod M
ユーザー te-shte-sh
提出日時 2017-04-25 12:20:16
言語 D
(dmd 2.106.1)
結果
WA  
実行時間 -
コード長 1,031 bytes
コンパイル時間 955 ms
コンパイル使用メモリ 94,052 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-03 12:59:20
合計ジャッジ時間 3,495 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 AC 76 ms
4,384 KB
testcase_02 AC 39 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 21 ms
4,380 KB
testcase_05 AC 1,499 ms
4,380 KB
testcase_06 AC 12 ms
4,380 KB
testcase_07 AC 160 ms
4,384 KB
testcase_08 AC 1 ms
4,384 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.algorithm, std.conv, std.range, std.stdio, std.string;
import std.math;

void main()
{
  auto t = readln.chomp.to!size_t;

  foreach (_; 0..t) {
    auto rd = readln.split.to!(long[]), n = rd[0], m = rd[1];
    if (n >= m) {
      writeln(0);
    } else {
      auto minF = minFactor(m);
      if (minF == -1) {
        auto r = m - 1;
        foreach (i; n+1..m)
          r = (r * modInv(i, m) % m + m) % m;
        writeln(r);
      } else {
        if (n >= m / minF) {
          writeln(0);
        } else {
          auto r = 1L;
          foreach (i; 2..n+1)
            r = r * i % m;
          writeln(r);
        }
      }
    }
  }
}

pure T minFactor(T)(T x)
{
  auto m = x.to!real.sqrt.to!T;
  foreach (f; 2..m+1)
    if (x % f == 0) return f;
  return -1;
}

pure T modInv(T)(T x, T m)
{
  T a, b;
  exEuclid(x, m, a, b);
  return a;
}

pure T exEuclid(T)(T a, T b, ref T x, ref T y)
{
  auto g = a;
  x = 1;
  y = 0;
  if (b != 0) {
    g = exEuclid(b, a % b, y, x);
    y -= a / b * x;
  }
  return g;
}
0