Kuro-orzz's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:warning: NumberTheory/Math/Factorial.h

Depends on

Code

#include "../../template.h"


// https://wiki.vnoi.info/translate/he/Wilsons-theorem
// Wilson theorem
// n > 1 is prime <=> (n-1)! ≡ -1 (mod n)
//
// Proof:
//    a^(n-2) ≡ a^(-1) (mod n) (Fermat's little theorem)
// => a^(n-2) * a ≡ 1 (mod n)
// Set b = a^(n-2)
// => ab ≡ 1 (mod n)
//
// Have a = b <=> a^2 ≡ 1 (mod n) <=> a = 1 or a = n-1
//
// So if a = 2,3,...,n-2 then a != b
// => we have (n-3)/2 distinct pairs (because with each a, b is unique)
// so we multiple all paris
// => 2.3...(n-2) ≡ 1 (mod n)
// => (n-1)! ≡ n-1 (mod n)

// Proof by contradiction:
// if n is not prime => n have divisors in range [2, n)
//                   => gcd((n-1)!, n) > 1
//                   => gcd(n-1, n) > 1 (contradiction)
int factmod(int n, int p) {
    vector<int> f(p);
    f[0] = 1;
    for (int i = 1; i < p; i++) {
        f[i] = f[i-1] * i % p;
    }
    int res = 1;
    while (n > 1) {
        if ((n/p) % 2) res = p - res;
        res = res * f[n % p] % p;
        n /= p;
    }
    return res;
}
// use for small prime p
#line 2 "template.h"

#include <bits/stdc++.h>
using namespace std;
 
#define ll long long
#define MOD (ll)(1e9+7)
#define all(x) (x).begin(),(x).end()
#define unique(x) x.erase(unique(all(x)), x.end())
#define INF32 ((1ull<<31)-1)
#define INF64 ((1ull<<63)-1)
#define inf (ll)1e18

#define vi vector<int>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define fi first
#define se second

const int mod = 998244353;

void solve();

int main(){
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    // cin.exceptions(cin.failbit);
    // int t; cin >> t;
    // while(t--)
        solve();
    cerr << "\nTime run: " << 1000 * clock() / CLOCKS_PER_SEC << "ms" << '\n';
    return 0;
}
#line 2 "NumberTheory/Math/Factorial.h"


// https://wiki.vnoi.info/translate/he/Wilsons-theorem
// Wilson theorem
// n > 1 is prime <=> (n-1)! ≡ -1 (mod n)
//
// Proof:
//    a^(n-2) ≡ a^(-1) (mod n) (Fermat's little theorem)
// => a^(n-2) * a ≡ 1 (mod n)
// Set b = a^(n-2)
// => ab ≡ 1 (mod n)
//
// Have a = b <=> a^2 ≡ 1 (mod n) <=> a = 1 or a = n-1
//
// So if a = 2,3,...,n-2 then a != b
// => we have (n-3)/2 distinct pairs (because with each a, b is unique)
// so we multiple all paris
// => 2.3...(n-2) ≡ 1 (mod n)
// => (n-1)! ≡ n-1 (mod n)

// Proof by contradiction:
// if n is not prime => n have divisors in range [2, n)
//                   => gcd((n-1)!, n) > 1
//                   => gcd(n-1, n) > 1 (contradiction)
int factmod(int n, int p) {
    vector<int> f(p);
    f[0] = 1;
    for (int i = 1; i < p; i++) {
        f[i] = f[i-1] * i % p;
    }
    int res = 1;
    while (n > 1) {
        if ((n/p) % 2) res = p - res;
        res = res * f[n % p] % p;
        n /= p;
    }
    return res;
}
// use for small prime p
Back to top page