1. 程式人生 > >H - Pairs Forming LCM(唯一分解定理)

H - Pairs Forming LCM(唯一分解定理)

align urn RM ctu rim tin div ans mes

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)‘.

大體題意:問1-n有多少對數使得lcm=n;

解題思路:

先來看個知識點:

素因子分解:n = p1 ^ e1 * p2 ^ e2 *..........*pn ^ en

for i in range(1,n):

ei 從0取到ei的所有組合

必能包含所有n的因子。

現在取n的兩個因子a,b

a=p1 ^ a1 * p2 ^ a2 *..........*pn ^ an

b=p1 ^ b1 * p2 ^ b2 *..........*pn ^ bn

gcd(a,b)=p1 ^ min(a1,b1) * p2 ^ min(a2,b2) *..........*pn ^ min(an,bn)

lcm(a,b)=p1 ^ max(a1,b1) * p2 ^ max(a2,b2) *..........*pn ^ max(an,bn)

題解:

先對n素因子分解,n = p1 ^ e1 * p2 ^ e2 *..........*pk ^ ek,

lcm(a,b)=p1 ^ max(a1,b1) * p2 ^ max(a2,b2) *..........*pk ^ max(ak,bk)

所以,當lcm(a,b)==n時,max(a1,b1)==e1,max(a2,b2)==e2,…max(ak,bk)==ek

當ai == ei時,bi可取 [0, ei] 中的所有數 有 ei+1 種情況,bi==ei時同理。

那麽就有2(ei+1)種取法,但是當ai = bi = ei 時有重復,所以取法數為2(ei+1)-1=2*ei+1。
除了 (n, n) 所有的情況都出現了兩次 那麽滿足a<=b的有 (2*ei + 1)) / 2 + 1個

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 
 8 const int maxn=1e7+10;
 9 const int maxnn=1e6;
10 int T;
11 long long a;
12 bool ip[maxn];
13 unsigned int p[maxnn],num;//輸入數據太大會導致超時
14 
15 void is_prime()
16 {
17     memset(ip,1,sizeof(ip));
18     ip[0]=ip[1]=0;
19     for(long long i=2;i<=maxn;i++)
20     {
21         if(ip[i])
22         {
23             p[num++]=i;
24             for(long long j=i+i;j<=maxn;j+=i)
25             {
26                 ip[j]=0;
27             }
28         }
29     }
30 }
31 
32 int main()
33 {
34     ios::sync_with_stdio(false);
35     cin>>T;
36     is_prime();
37     for(int i=1;i<=T;i++)
38     {
39         cin>>a;
40         long long ans=1;
41         for(int i=0;i<num&&p[i]*p[i]<=a;i++)
42         {
43             if(a%p[i]==0)
44             {
45                 int cnt=0;
46                 while(a%p[i]==0)
47                 {
48                     a/=p[i];
49                     cnt++;
50                 }
51                 ans*=(2*cnt+1);
52             }
53         }
54         if(a>1) ans*=(2*1+1);
55 
56         cout<<"Case"<<" "<<i<<":"<<" "<<(ans+1)/2<<endl;
57     }
58     return 0;
59 }

H - Pairs Forming LCM(唯一分解定理)