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 |
题意:求最小公倍数是N的(i,j)有多少对
思路:先对n进行素因子分解,n=p1^e1*p2^e2*…*pk^ek
a=p1^a1*p2^a2*…*pk^ak
b=p1^b1*p2^b2*…*pk^bk
对于a,b它们的最小公倍数为n,则a1<=e1,b1<=e1,则(a1,b1)有2*(e1+1)-1对则总的对数有t=(2*e1+1)*(2*e2+1)....,其中除了(n,n),其他的都重复了两次则答案为(t+1)/2.
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAX 10001000
#define LL long long
using namespace std;
bool vis[MAX];
LL prim[MAX/10];
int a[1100],b[1100],cnt,k=0;
void getprim()
{
for(LL i=2;i<MAX;i++)
if(!vis[i])
{
prim[k++]=i;
for(LL j=i*i;j<MAX;j+=i)
vis[j]=true;
}
}
void init(LL n)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
cnt=0;
for(LL int i=0;prim[i]*prim[i]<=n;i++)
{
if(n%prim[i]==0)
{
a[cnt]=prim[i];
while(n%prim[i]==0)
{
b[cnt]++;
n=n/prim[i];
}
cnt++;
}
}
if(n!=1)
{
a[cnt]=n;
b[cnt++]=1;
}
}
int main()
{
int t,m=1;
LL n;
getprim();
scanf("%d",&t);
while(t--)
{
scanf("%lld",&n);
init(n);
LL ans=1;
for(LL i=0;i<cnt;i++)
{
ans=ans*(2*b[i]+1);
}
ans=(ans+1)/2;
printf("Case %d: %lld\n",m++,ans);
}
return 0;
}