[bzoj2226][SPOJ5971]LCMSUM
2015-10-14 23:07
253 查看
2226: [Spoj 5971] LCMSum
Time Limit: 20 Sec Memory Limit: 259 MBSubmit: 949 Solved: 427
[Submit][Status][Discuss]
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
首先我们先化简一下式子:
∑i=1nlcm(i,n)
∑i=1ni∗ngcd(i,n)
n∗∑i=1nigcd(i,n)
n∗∑d|n∑i=1nid(gcd(i,n)==d)
n∗∑d|n∑j=1ndj(gcd(i,nd)==1)(j=id)
n∗∑d|n∑j=1dj(gcd(i,d)==1)(nd和d等价)
令f[i]=∑i=1di(gcd(i,d)==1)
f[i]就表示1~d中与i互质的数的和。怎样去求f[i]呢?
首先如果gcd(x,n)==1,那么gcd(n-x,n)==1
证明:如果gcd(n-x,n)=d(d!=1) 那么n-x=d(n1-x1),那么gcd(x,n)=d>1所以得证。
根据上面的这个性质,我们就可以将与d互质的数分为x和d-x两部分。因因为x+d-x=d,所以
f[i]=∑i=1di(gcd(i,d)==1)=d∗phi[d]2
ans=∑d|nd∗phi[d]2
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> using namespace std; const int N=1000010; #define LL long long int n,T,phi ; inline void prepare(){ int i,j; phi[1]=1; for(i=2;i<=N;++i) if(!phi[i]) for(j=i;j<=N;j+=i){ if(!phi[j]) phi[j]=j; phi[j]=phi[j]/i*(i-1); } } inline void calc(int x){ int i; LL ans=0; for(i=1;i<=sqrt(x);++i) if(!(x%i)){ if(i!=1) ans+=(LL)i*(LL)phi[i]/2; else ans+=1; if(x/i!=i) ans+=(LL)(x/i)*(LL)phi[x/i]/2; } printf("%lld\n",ans*(LL)(x)); } int main(){ prepare(); scanf("%d",&T); while(T--){ scanf("%d",&n); calc(n); } }
相关文章推荐
- 进程&线程小结
- worker_pool的例子
- 浅析c++中的类型转换--const_cast
- IndexedDB: 浏览器里内置的数据库简介
- Application.mk
- 浅析c++中的类型转换--const_cast
- 算法(一)求链表中的倒数第K 个结点
- ENVI遥感影像自然真彩色增强方法
- 实现基于Task的异步模式
- 海思Hi3518内核编译过程中问题点记录
- ndk-build
- 地图定位异常问题
- struts2标签Tags的用法
- Spring官网改版后下载
- 新版WampServer项目路径前面没有localhost
- 饭碗是要靠抢的
- Sql Server 分页查询
- C++文件(夹)选择对话框
- 安卓TV开发(十) 智能电视开发之在线视频直播
- 安卓TV开发(十) 智能电视开发之在线视频直播