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
15
2
3
4
6
8
10
12
15
18
20
21
24
25
27
29
Sample Output
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
解题报告
素因子分解一定要打素数表,不然超时
分析过程:
若 LCM(a,b)=n ,即
则a,b的组合个数
由于a < b , 但a=b时只有一个,那么答案就是
#include<stdio.h>
#define MAX_N 10000100
#define PN 664581
#define I p[i]
typedef long long LL;
bool vis[MAX_N];
int p[PN];
void init(){
for(int i=2;i*i<MAX_N;i++)
if(!vis[i])
for(int k=i*i;k<MAX_N;k+=i)
vis[k]=true;
for(int i=2,u=0;i<MAX_N;i++)
if(!vis[i]) p[u++]=i;
}
LL solve(LL n){
LL res=1;
for(LL i=0;(LL)I*I<=n;i++)
if(n%I==0){
LL cnt=0;
while(n%I==0) cnt++,n/=I;
res*=2*cnt+1;
}
if(n>1) res*=3;
return res/2+1;
}
int main()
{
init();
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++){
LL n;
scanf("%lld",&n);
printf("Case %d: %lld\n",t,solve(n));
}
return 0;
}

本文介绍了一种高效计算给定整数n下成对整数(i, j)的数量的方法,这些整数对满足最小公倍数等于n的条件。通过对n进行素因子分解并利用组合数学原理,提出了一种快速算法。
1724

被折叠的 条评论
为什么被折叠?



