题目链接:
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Find the result of the following code:
long long pairsFormLCM( int n ) {
long long res = 0; for( int i = 1; i <= n; i++ ) for( int j = i; j <= n; j++ ) if( lcm(i, j) == n ) res++; // lcm means least common multiple return res;}A straight forward implementation of the code may time out. If you analyze the code, you will find that the code actually counts the number of pairs (i, j) for which lcm(i, j) = n and (i ≤ j).
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 1014).
Output
For each case, print the case number and the value returned by the function 'pairsFormLCM(n)'.
Sample Input | Output for Sample Input |
15 2 3 4 6 8 10 12 15 18 20 21 24 25 27 29 | Case 1: 2 Case 2: 2 Case 3: 3 Case 4: 5 Case 5: 4 Case 6: 5 Case 7: 8 Case 8: 5 Case 9: 8 Case 10: 8 Case 11: 5 Case 12: 11 Case 13: 3 Case 14: 4 Case 15: 2 |
题意:
求1到n(1e14)之内,有多少对数(i,j),其中i<=j,使得LCM(i,j)= n,LCM为最小公倍数。
题解:
1.设pi为第i个质数。设两个数A、B,他们可表示为:A = p1^a1 * p2^a2…… ,B = p1^b1 * p2^b2……。
那么他们的最小公倍数为:LCM(A, B) = p1^max(a1,b1) * p2^max(a2, b2)……。
2.对n进行质因数分解,得到: n = p1^c1 * p2^c2……。当 LCM(A, B) = n时, ci = max(ai, bi),即要么 ci = ai,要么ci = bi。
3 当ci = ai时, bi的可选择范围为[0,ci]共ci+1种;同理当ci = bi时,ai也有ci+1种选择。但是 (ai=ci,bi=ci)被重复计算了一次,所以对于素数pi,总共有 2*ci+1种选择。所以,当不考虑A、B的大小时,总共有 ∏ 2*ci+1对(A,B),使得 LCM(A, B) = n。
4.再考虑回A、B的大小限制,即A<=B,可知除了A = B = n时,其他的组合都出现了两次,即(A,B)和(B,A)都存在,而要门只需要A<=B的那一个。总的来说,最终有 ((∏ 2*ci+1)+1)/2对 (A,B)满足条件。
代码如下:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include