【bzoj2226】【spoj5971】【lcmsum】【数论】

来源:互联网 发布:小米数据迁移 分身 编辑:程序博客网 时间:2024/06/03 08:06

Description

Given n, calculate the sum LCM(1,n) + LCM(2,n) + .. + LCM(n,n), where LCM(i,n) denotes the Least Common Multiple of the integers i and n.

Input

The first line contains T the number of test cases. Each of the next T lines contain an integer n.

Output

Output T lines, one for each test case, containing the required sum.

Sample Input

3
1
2
5

Sample Output

1
4
55

HINT

Constraints

1 <= T <= 300000
1 <= n <= 1000000

题解:

首先题目要求的是

                            

变形一下就成了 

                         

继续化简一下

      

定义p[i]为1-i中与i互质的数的和。

那么答案就是


复杂度并不是很科学。然而时限两秒,抱着试试的心态就A了。

代码:

#include<iostream>#include<cstdio>#include<cmath>#include<cstring> using namespace std;int t,phi[1000001],p[1000001],n,temp;bool f[1000001];void pre(int x){    phi[1]=1;    for (int i=2;i<=x;i++){       if (!f[i]){phi[i]=i-1;p[++p[0]]=i;}       for (int j=1;j<=p[0]&&p[j]*i<=x;j++){          f[p[j]*i]=true;          if (i%p[j]==0){phi[i*p[j]]=phi[i]*p[j];break;}          else phi[i*p[j]]=phi[i]*phi[p[j]];        }    }   }long long work(int x){if (x==1) return 1ll;else return (long long)x*phi[x]/2;} long long cal(int x){  long long ans(0);temp=sqrt(x);   for (int i=1;i<=temp;i++)    if (x%i==0){ans+=work(i);ans+=work(x/i);}  if (temp*temp==x) ans-=work(temp);  return ans;}int main(){   pre(1000000);scanf("%d",&t);   while (t--){scanf("%d",&n);printf("%lld\n",cal(n)*n);}} 


0 0
原创粉丝点击