【bzoj2226】[Spoj 5971] LCMSum 欧拉函数
題目描述
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.
輸入
The first line contains T the number of test cases. Each of the next T lines contain an integer n.
輸出
Output T lines, one for each test case, containing the required sum.
樣例輸入
3
1
2
5
樣例輸出
1
4
55
題解
歐拉函數
其中需要解釋一下最后一個式子的推導過程:
有一個結論:當n>2時,小于n且與n互質的數的和等于$\frac{n·\varphi(n)}2$,因為若k與n互質,則n-k一定也與n互質。
當n=2時這個關系式在數值上成立,當n=1時不成立,需要特殊處理。
所以可以先篩歐拉函數,然后枚舉d,將1~n所有能夠整除d的數的答案加上$\frac{d·\varphi(d)}2$。最后輸出答案時再加一點處理即可。
時間復雜度為調和級數的$O(n\ln n)$
#include <cstdio> #include <algorithm> #define N 1000010 using namespace std; typedef long long ll; const int m = 1000000; int phi[N] , prime[N] , tot; ll f[N]; bool np[N]; int main() {int i , j , T , n;for(i = 2 ; i <= m ; i ++ ){if(!np[i]) phi[i] = i - 1 , prime[++tot] = i;for(j = 1 ; j <= tot && i * prime[j] <= m ; j ++ ){np[i * prime[j]] = 1;if(i % prime[j] == 0){phi[i * prime[j]] = phi[i] * prime[j];break;}else phi[i * prime[j]] = phi[i] * (prime[j] - 1);}}for(i = 2 ; i <= m ; i ++ )for(j = i ; j <= m ; j += i)f[j] += (ll)i * phi[i] / 2;scanf("%d" , &T);while(T -- ) scanf("%d" , &n) , printf("%lld\n" , (f[n] + 1) * n);return 0; }?
轉載于:https://www.cnblogs.com/GXZlegend/p/7015873.html
總結
以上是生活随笔為你收集整理的【bzoj2226】[Spoj 5971] LCMSum 欧拉函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 装饰器 and 闭包函数 未完。。。
- 下一篇: 可视化之Earth NullSchool