結果

問題 No.109 N! mod M
ユーザー nebukuro09nebukuro09
提出日時 2017-11-12 21:32:34
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 2,997 ms / 5,000 ms
コード長 1,117 bytes
コンパイル時間 771 ms
コンパイル使用メモリ 104,984 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-03 16:52:24
合計ジャッジ時間 4,930 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop;

bool is_prime(long n) {
    for (long i = 2; i * i <= n; ++i)
        if (n % i == 0)
            return false;
    return true;
}

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

long solve() {
    auto s = readln.split.map!(to!long);
    auto N = s[0];
    auto M = s[1];

    if (M == 1)
        return 0;
    if (N == 0)
        return 1;
    if (N >= M)
        return 0;

    if (is_prime(M)) {
        long ret = M - 1;
        for (long cnt = M - 1; cnt > N; --cnt)
            ret = ret * powmod(cnt, M-2, M) % M;
        return ret;
    } else if (M < 10^^6) {
        long ret = 1;
        for (long i = 2; i <= N; ++i)
            ret = ret * i % M;
        return ret;
    } else {
        return 0;
    }
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--)
        solve.writeln;
}
0