結果

問題 No.109 N! mod M
ユーザー mamekinmamekin
提出日時 2015-02-01 12:31:00
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 1,461 ms / 5,000 ms
コード長 1,743 bytes
コンパイル時間 1,221 ms
コンパイル使用メモリ 87,712 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:23:35
合計ジャッジ時間 2,980 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
using namespace std;

// 素数判定
bool primalityTest(long long n)
{
    if(n < 2)
        return false;
    for(long long i=2; i*i<=n; ++i){
        if(n % i == 0)
            return false;
    }
    return true;
}

// a,b の最大公約数と、ax + by = gcd(a,b) となる x,y を求める
long long extgcd(long long a, long long b, long long &x, long long &y) {
    long long g = a;
    if(b != 0){
        g = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    }else{
        x = 1;
        y = 0;
    }
    return g;
}

// ax ≡ gcd(a, m) (mod m) となる x を求める
// a, m が互いに素ならば、関数値は mod m での a の逆数となる
long long mod_inverse(long long a, long long m)
{
    long long x, y;
    extgcd(a, m, x, y);
    return (x % m + m) % m;
}

int main()
{
    int t;
    cin >> t;

    while(--t >= 0){
        int n, m;
        cin >> n >> m;

        long long ret;
        if(n < 200000){
            ret = 1 % m;
            for(int i=2; i<=n; ++i){
                ret *= i;
                ret %= m;
            }
        }
        else if(n >= m || !primalityTest(m)){
            ret = 0;
        }
        else{
            ret = m - 1;
            for(int i=n+1; i<=m-1; ++i){
                ret *= mod_inverse(i, m);
                ret %= m;
            }
        }
        cout << ret << endl;
    }

    return 0;
}
0