Skip to main content

DCEPC11B - Boring Factorials


Ref Link

#include <iostream>

using namespace std;
#define LL long long

LL fastExpo(LL a, LL b, LL mod)
{
    LL x = 1;
    LL y = a;

    while(b > 0)
    {
        if(b & 1)
        {
            x = (x * y) % mod;
        }

        y = (y * y) % mod;

        b = b >> 1;
    }

    return x;
}

int main()
{
    int t;
    LL n, p, i, temp;
    LL result = - 1;

    cin >> t;
    while(t--)
    {
        cin >> n >> p;

        result = -1;
        temp = 1;

        if(n >= p)
        {
            cout << "0\n";
            continue;
        }

        if(n == p - 1)
        {
            cout << p - 1 << endl;
            continue;
        }

        for(i = n + 1; i < p; i++)
        {
            temp = (temp * i) % p;
        }

        result = result * fastExpo(temp, p - 2, p);

        cout << p + result << endl;
    }
    return 0;
}

Comments