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 = p1^a1 * p2^a2 * p3^a3 * ...* pn^an 。 其中p1,p2....pn为素数。
思路:
n可以表示为:n=p1^x1 * p2^x1 * .... * pk^xk。
假设lcm(a,b) == n;
a = p1^c1 * p2^c2 ..... pk^ck。
b = p1^e1 * p2^e2 .... pk^ek。
xi = max(ci, ei)。
对于有序数对(a,b),有唯一分解定理知,每一个素因数的幂都决定了一个独一无二的数。
求(a,b)的种数就可以转化为求(ci,ei)的种数:num = (2*x1+1)*(2*x2+1).....(2*xk+1)。
因为是有序数对,最后在除于二。
#include<cstdio>
#include<cstring>
const int maxn = 1e7+100;
bool vis[maxn];
long long b[maxn/10];
long long k;
void priem() //素数打表
{
long long i , j;
memset(vis,false,sizeof(vis));
memset(b,0,sizeof(b));
for(k = 0,i = 2 ; i < maxn ; i++)
{
if(!vis[i])
{
b[k++] = i;
for(j = i * i ; j < maxn ; j += i)
vis[j] = true;
}
}
}
int main()
{
int T,kcase = 1;
priem();
long long n;
scanf("%d",&T);
while(T--)
{
scanf("%lld",&n);
long long ans = 1;
for(long long i = 0 ; i < k && b[i] * b[i] <= n ; i++)
{
long long cnt = 0;
while(n % b[i] == 0)
{
cnt++;
n /= b[i];
}
ans *= (2 * cnt + 1);
}
if(n > 1) //就是因为上面for条件的原因;b[i]*b[i]<=n,
//当不满足这个条件的时候就应该还有一个素数的一次方
ans *= 3;
printf("Case %d: %lld\n",kcase++,ans / 2 + 1);
}
return 0;
}