題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=6069
Counting Divisors
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 3271 Accepted Submission(s): 1220
Problem Description
In mathematics, the function d(n) denotes the number of divisors of positive integer n.
For example, d(12)=6 because 1,2,3,4,6,12 are all 12’s divisors.
In this problem, given l,r and k, your task is to calculate the following thing :
(∑i=lrd(ik))mod998244353
Input
The first line of the input contains an integer T(1≤T≤15), denoting the number of test cases.
In each test case, there are 3 integers l,r,k(1≤l≤r≤1012,r−l≤106,1≤k≤107).
Output
For each test case, print a single line containing an integer, denoting the answer.
Sample Input
3
1 5 1
1 10 2
1 100 3
Sample Output
10
48
2302
Source
2017 Multi-University Training Contest - Team 4
首先說一下約數個數定理:
簡要概括一下:
任意一個整數都能由素數的乘積表示:n=p1^a1*p2^a2……..pn^an;
這裏p1,p2……pn均爲質數,其中指數a1,a2……an是正整數
那麼d(n)=(a1+1)(a2+1)…*(an+1)
進而d(n^k)=(k*a1+1)(k*a2+1)…*(k*an+1)
思路:
d(n)裏n的取值最大1e12,那麼要判斷它是不是素數只需計算到sqrt(n),所以素數表只需打到1e6,如果它是個合數,就可以用打好的表裏的素數進行分解,如果經過所有分解最後還大於1,那麼剩下的這個數也是一個素數,還是一個大於1e6的素數,所作貢獻爲k+1。
代碼:
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<cmath>
#include<cstring>
#include<bits/stdc++.h>
using namespace std;
const long long mod=998244353;
long long ans,l,r,k,len;
int T;
long long f[100000],num[1000005],a[1000005],vis[1000005];
void pre()
{//素數篩法打表
int flag;
len=0;
for(int i=2;i<=1e6;i++)
{
for(int j=i+i;j<=1e6;j+=i)
vis[j]=1;
}
for(int i=2;i<=1e6;i++)
{
if(!vis[i])
f[++len]=i;
}
return;
}
int main()
{
pre();//打印1~1e6之間的素數表
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld%lld",&l,&r,&k);
for(int i=0;i<=r-l;i++)
{
num[i]=1;//l+i這個數字所含有的約數個數
a[i]=i+l;//數字本身
}
ans=0;//存放輸出
for(int i=1;i<=len;i++)
{//將1e6內的所有素數遍歷一遍,如果能整除則一直分解(即除以約數(次數不限))同時計算約數的冪次方
//利用約數個數定理可以計算
long long s=(l/f[i])*f[i];
if(s<l)
s+=f[i];//從s開始是爲了讓該數能被f[i]整除
for(long long j=s;j<=r;j+=f[i])
{
long long w=0;//w表示最終可被f[i]的w次冪整除
while(a[j-l]%f[i]==0)
{//一直到不能整除爲止
a[j-l]/=f[i];
w++;
}
num[j-l]=(num[j-l]*(w*k+1))%mod;//約數定理的應用
}
}
for(int i=0;i<=r-l;i++)
if(a[i]>1)//如果到最後還不爲1的話,表示該數還含有一個很大的素數(大於1e6)
num[i]=num[i]*(k+1)%mod;
for(int i=0;i<=r-l;i++)
ans=(ans+num[i])%mod;//累加區間內每個數字的約數個數和
printf("%lld\n",ans);
}
return 0;
}