結果
問題 | No.109 N! mod M |
ユーザー |
|
提出日時 | 2016-10-18 20:20:32 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 2,775 ms / 5,000 ms |
コード長 | 2,809 bytes |
コンパイル時間 | 1,249 ms |
コンパイル使用メモリ | 92,544 KB |
実行使用メモリ | 6,944 KB |
最終ジャッジ日時 | 2024-06-22 05:02:58 |
合計ジャッジ時間 | 4,676 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 9 |
ソースコード
#include <iostream>#include <vector>#include <map>#include <cmath>#include <cassert>#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))#define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i))typedef long long ll;using namespace std;template <class T> void setmax(T & a, T const & b) { if (a < b) a = b; }vector<int> sieve_of_eratosthenes(int n) { // enumerate primes in [2,n] with O(n log log n)vector<bool> is_prime(n+1, true);is_prime[0] = is_prime[1] = false;for (int i = 2; i*i <= n; ++i)if (is_prime[i])for (int k = i+i; k <= n; k += i)is_prime[k] = false;vector<int> primes;for (int i = 2; i <= n; ++i)if (is_prime[i])primes.push_back(i);return primes;}map<ll,int> factors(ll n, vector<int> const & primes) {map<ll,int> result;for (int p : primes) {if (n < p *(ll) p) break;while (n % p == 0) {result[p] += 1;n /= p;}}if (n != 1) result[n] += 1;return result;}ll powi(ll x, ll y) { // O(log y)assert (y >= 0);ll z = 1;for (ll i = 1; i <= y; i <<= 1) {if (y & i) z *= x;x *= x;}return z;}ll powi(ll x, ll y, ll p) { // O(log y)assert (y >= 0);x = (x % p + p) % p;ll z = 1;for (ll i = 1; i <= y; i <<= 1) {if (y & i) z = z * x % p;x = x * x % p;}return z;}ll inv(ll x, ll p) { // p must be a prime, O(log p)assert ((x % p + p) % p != 0);return powi(x, p-2, p);}int main() {const vector<int> primes = sieve_of_eratosthenes(sqrt(1e9) + 3);int t; cin >> t;while (t --) {ll n, m; cin >> n >> m;assert (0 <= n and n <= 1e9);assert (1 <= m and m <= 1e9);assert (m <= n + 1e5);map<ll,int> ps = factors(m, primes);ll ans;if (ps.empty()) { // m is 1ans = 0;} else if (ps.size() == 1 and ps.begin()->second == 1) { // m is a primeif (m <= n) {ans = 0;} else {ans = m - 1;repeat_from (i,n+1,m) {ans = ans * inv(i, m) % m;}}} else { // m is a compositell limit = 0;for (auto it : ps) {ll p; int cnt; tie(p, cnt) = it;int k = 0; while (k * (k+1) / 2 < cnt) ++ k;setmax(limit, p * k);}if (limit <= n) {ans = 0;} else {ans = 1;repeat_from (i,1,n+1) {ans = ans * i % m;}assert (ans != 0);}}cout << ans << endl;}return 0;}