Pairs Forming LCM (LightOJ - 1236)【简单数论】【质因数分解】【算术基本定理】(未完成)
标签: 入门讲座题解 数论
题目描述
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
题意
给定(n)。
求(sum_{i = 1}^{n} sum_{j = i}^{n} [lcm(i, j) = n])的值。
解析
通过代码
/*
Problem
LightOJ - 1236
Status
Accepted
Time
410ms
Memory
19664kB
Length
1299
Lang
C++
Submitted
2019-11-25 15:30:08
Shared
RemoteRunId
1640611
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e7 + 50;
bool vis[MAXN];
int prime[MAXN / 10], p[MAXN / 10], m = 0, cnt;
void fill_0()
{
for(int i = 1; i <= cnt; i ++)
p[i] = 0;
return;
}
void get_prime() //线性筛,筛出1e7以内全部质数.
{
vis[1] = 1;
for(int i = 2; i <= int(1e7 + 5); i ++){
if(!vis[i])
prime[++ m] = i;
for(int j = 1; j <= m && i * prime[j] <= int(1e7 + 5); j ++){
vis[i * prime[j]] = 1;
if(i % prime[j] == 0)
break;
}
}
return;
}
void get_fact(ll x)
{
fill_0(); //将p数组归零.
cnt = 0;
for(int i = 1; i <= m && 1ll * prime[i] * prime[i] <= x; i ++){ //以下求得一个数的质因数分解每个质数的幂次.
if(x % prime[i] == 0){
cnt ++;
while(x % prime[i] == 0){
p[cnt] ++;
x /= prime[i];
}
}
}
if(x != 1)
p[++ cnt] = 1;
return;
}
ll work()
{
ll res = 1;
for(int i = 1; i <= cnt; i ++)
res *= 1ll * (2 * p[i] + 1);
return (res + 1) >> 1;
}
int main()
{
get_prime();
int times, _case = 0;
scanf("%d", ×);
while(times --){
ll x;
scanf("%lld", &x);
get_fact(x);
printf("Case %d: %lld
", ++ _case, work());
}
return 0;
}