In this article, pk denotes the k-th smallest prime number.
Statement
Given N,M, calculate:
σ0(N!)modM.
Solution
Let N!=pi≤N∏pici.
By Legendre’s theorem, the exponent of pi in N! is:
c=1pic≤N∑⌊picN⌋.
Therefore:
σ0(N!)=pi≤N∏σ0(pici)=pi≤N∏(ci+1)=pi≤N∏c=1pic≤N∑⌊picN⌋+1.
Let B←⌊N⌋.
Notice that when pi∈(B,N], c=1pic≤N∑⌊picN⌋=⌊piN⌋.
Thus:
σ0(N!)=pi≤B∏c=1pic≤N∑⌊picN⌋+1pi∈(B,N]∏(⌊piN⌋+1).
First part:
pi≤B∏c=1pic≤N∑⌊picN⌋+1.
This part can be calculated after precomputing primes in [2,B].
The number of primes in [2,B] is O(logNN), and calculating a single c=1pic≤N∑⌊picN⌋ takes O(logN).
Thus the first part is calculated in O(N).
Second part:
pi∈(B,N]∏(⌊piN⌋+1).
Consider the floor division trick. For a block [l,r], its contribution is:
(⌊lN⌋+1)(π(r)−π(l−1)).
Precompute all π(i) (i≤N) using the linear sieve, which has complexity of O(N).
The complexity of the floor division trick is O(NlogN).
Thus the second part is calculated in O(NlogN).
Total complexity: O(N+TNlogN).
Code
Note that M may be 1.
C++#include<bits/stdc++.h>
#define int long long
const int _N=5510;
const int N=1e8+10;
using namespace std;
int T;
int n,m,b,ans;
int _in1[_N],_in2[_N];
int cnt,p[N];
bool vis[N];
int pi[N];
inline int read(){
int ret=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')ret=ret*10+(ch&15),ch=getchar();
return ret*f;
}
int _sqrt(int x){
int ret=floor(sqrtl(x));
while((ret+1)*(ret+1)<=x)ret++;
return ret;
}
int qpow(int x,int y){
x%=m;
int ret=1;
while(y){
if(y&1)ret=ret*x%m;
x=x*x%m;
y>>=1;
}
return ret;
}
void _init(int _n){
for(int i=2;i<=_n;i++){
if(!vis[i])p[++cnt]=i;
pi[i]=cnt;
for(int j=1;j<=cnt&&i*p[j]<=_n;j++){
vis[i*p[j]]=1;
if(!(i%p[j]))break;
}
}
}
int _cal(int p_i){
int ret=1;
for(int _p=p_i;_p<=n;_p*=p_i)ret+=n/_p;
return ret;
}
void _solve(int _n,int _m){
n=_n,m=_m;
b=_sqrt(n);
ans=1ll%m;
for(int i=1;i<=cnt&&p[i]<=b;i++)ans=ans*_cal(p[i])%m;
for(int l=b+1,r;l<=n;l=r+1){
r=n/(n/l);
ans=ans*qpow(n/l+1,pi[r]-pi[l-1])%m;
}
printf("%lld\n",ans);
}
signed main(){
T=read();
int mx=0;
for(int i=1;i<=T;i++)_in1[i]=read(),_in2[i]=read(),mx=max(mx,_in1[i]);
_init(mx);
for(int i=1;i<=T;i++)_solve(_in1[i],_in2[i]);
return 0;
}
Afterword
Why not try DIVFACT4?