I can calculate for $O(n)$ for a naive calculation.You are given an integer n.
Find $n! \mod 1,000,000,007$.
But if $n \le 1,000,000,000$, I can't calculate for a few seconds.
Do you have an "efficient" algorithm?
If you have, please post.
I can calculate for $O(n)$ for a naive calculation.You are given an integer n.
Find $n! \mod 1,000,000,007$.
Code: Select all
#include <iostream>
using namespace std;
int modpow(int a, int b, int m) {
int ret = 1;
for(int i = 30; i >= 0; i--) {
ret = 1LL * ret * ret % m;
if(b & (1 << i)) ret = 1LL * ret * a % m;
}
return ret;
}
int n; const int mod = 1000000007;
int main() {
cin >> n;
int ret = 1;
if(n < 970000000) {
for(int i = 1; i <= n; i++) ret = 1LL * ret * i % mod;
}
else {
ret = mod - 1;
for(int i = mod - 1; i > n; i--) ret = 1LL * ret * modpow(i, mod - 2, mod) % mod;
}
cout << ret << endl;
return 0;
}
Code: Select all
#include <iostream>
using namespace std;
int modpow(int a, int b, int m) {
int ret = 1;
for(int i = 30; i >= 0; i--) {
ret = 1LL * ret * ret % m;
if(b & (1 << i)) ret = 1LL * ret * a % m;
}
return ret;
}
int modinv(int x, int m) {
return modpow(x, m - 2, m);
}
int n; const int mod = 1000000007;
int main() {
cin >> n;
int ret = 1;
if(n < mod / 2) {
for(int i = 1; i <= n; i++) ret = 1LL * ret * i % mod;
}
else {
ret = mod - 1;
int mul = 1;
for(int i = mod - 1; i > n; i--) mul = 1LL * mul * i % mod;
ret = 1LL * ret * modinv(mul, mod) % mod;
}
cout << ret << endl;
return 0;
}
Code: Select all
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
using ll = long long;
int pow_mod(int b, int e, int mod) {
int ret = 1;
for (; e; e >>= 1, b = ll(b) * b % mod) {
if (e & 1) ret = ll(ret) * b % mod;
}
return ret;
}
int fact_valuation(int n, int p) {
int ret = n /= p;
while (n >= p) {
n /= p;
ret += n;
}
return ret;
}
template <int p>
int fact_mod(int n) {
if (n >= p) return 0;
if (n * 2 > p) {
int ret = fact_mod<p>(p - n - 1);
ret = (p - n - 1) & 1 ? ret : p - ret;
return pow_mod(ret, p - 2, p);
}
vector<int> ns;
for (int i = n; i > 1; i /= 5)
for (int j = i; j > 1; j /= 3)
for (int k = j; k > 1; k >>= 1)
ns.push_back(k);
std::sort(ns.begin(), ns.end());
const int d[8] = {6, 4, 2, 4, 2, 4, 6, 2};
int ret = 1, prod = 1, i = 1, r = 0;
for (auto end : ns) {
for (; i <= end; i += d[r & 7], ++r) {
prod = ll(prod) * i % p;
}
ret = ll(ret) * prod % p;
}
ret = ll(ret) * pow_mod(2, fact_valuation(n, 2), p) % p;
ret = ll(ret) * pow_mod(3, fact_valuation(n, 3), p) % p;
ret = ll(ret) * pow_mod(5, fact_valuation(n, 5), p) % p;
return ret;
}
int main() {
const int mod = 1e9 + 7;
printf("%d\n", fact_mod<mod>((mod - 1) / 2));
}