lightoj 1236 - Pairs Forming LCM

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
分析:求LCM(i,j)==n的组数。
i=p1^a1*p2^a2*p3^a3……ps^as;
j=p1^b1*p2^b2*p3^b3……ps^b3;
n=p1^c1*p2^c2*p3^c3……ps^cs;
lcm(i,j)==n 即 p1^max(a1,b1)p2^max(a2,b2)……;
即满足:max(ai,bi)==ci,求满足条件的种数。
先考虑有序数对。
1:ai=ci,bi=[0,ei] 有 ei+1种
2:bi=ci, ai=[0,ei], 并 ai==ci,bi==ci,上面出现过了,所以减一 有 2*ei+1 种。
对于无序对来说,Lcm(n,n)只出现过一次(ei==ai==bi) 所以 解为:
((2*e1+1)*(2*e2+1)……(2*es+1)+1)/2;
来个例子吧:n=2^3时;
当 a1=3, b1=3,2,1,0;
b1=3,a1=3,2,1,0;
考虑有序对 时 (3,3)重复了一次,所以减去一次。
当有多项相乘的时候 是一样的,用乘法规则。

第一次遇到 ml,我也懵逼了。看了别人的,用boll类型代替int, bool 只占1字节,int 占4字节。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<cstdio>
using namespace  std;
const  int maxn=1E7+5;
bool vis[maxn] ;
long long prime[maxn/10],len=0;
int   factor[100000];

void is_prime()
{
    for(int i=2;i<maxn;i++)
    {
        if(!vis[i])
        {
            prime[len++]=i;
            for(int j=i+i;j<maxn;j+=i)
            vis[j]=1;
        }
    }    
}


void getprimefactor(long long nn)
{
    int cas=0;
    for(int i=0;i<len&&prime[i]*prime[i]<=nn;i++)
    {
            while(nn%prime[i]==0)
            {
                factor[cas]++;
                nn/=prime[i];
            } 
          if(factor[cas])
          cas++;
    }
    if(nn>1)
    factor[cas]=1;
}

int main()
{
    is_prime();
    int k=1,t;
    scanf("%d",&t); 
    while(t--)
    {
        long long n;
        scanf("%lld",&n);   
        long long  sum=1;
    memset(factor,0,sizeof(factor));
        getprimefactor(n);
        for(int i=0;;i++)
        {
            if(!factor[i])
            break;
            sum=sum*(2*factor[i]+1);
        }
        sum++;
        printf("Case %d: %lld\n",k++,sum/2); 
    }
    return 0;
}

你可能感兴趣的:(lightoj 1236 - Pairs Forming LCM)