题目
思路
-
g
c
d
(
x
,
y
)
=
p
x
,
y
∈
[
1
,
N
]
gcd(x, y) = p\;\;x,y\in[1,N]
gcd(x,y)=px,y∈[1,N]
- 转换为
g
c
d
(
x
p
,
y
p
)
=
1
x
p
,
y
p
∈
[
1
,
N
p
]
gcd(\frac{x}{p}, \frac{y}{p}) = 1\;\;\frac{x}{p},\frac{y}{p}\in[1,\frac{N}{p}]
gcd(px,py)=1px,py∈[1,pN]
注意这里,确定了p之后才确定了取值集合(不同p值下的取值集合,哪怕元素值一样意义也不一样,因为对应的p值不一样,最终还原出的x不一样,最开头的gcd值p也不一样),这个区间内的每个整数都要欧拉函数化,为下文的前缀和埋下伏笔
- 处理欧拉数组 φ [ i ] \varphi[i] φ[i],这里 φ [ 1 ] ≠ 1 \varphi[1] \neq 1 φ[1]=1,下文单独拿出来算
- 分三种情况考虑 x p > y p ( φ ( x p ) ) \frac{x}{p} > \frac{y}{p}\;\;(\varphi(\frac{x}{p})) px>py(φ(px)) 、 x p < y p ( φ ( y p ) ) \frac{x}{p} < \frac{y}{p}\;\; (\varphi(\frac{y}{p})) px<py(φ(py))、 x p = y p = 1 ( 1 ) \frac{x}{p} = \frac{y}{p} = 1\;\;(1) px=py=1(1)
- 构造 s [ t ] = ∑ i = 1 t φ [ i ] s[t] = \sum_{i=1}^{t}\varphi[i] s[t]=∑i=1tφ[i]
- 每个 p p p 下的个数表达式为 s [ n p ] ⋅ 2 + 1 s[\frac{n}{p}] \cdot 2+1 s[pn]⋅2+1
- 计算
- 遍历 p p ≤ n p \;\; p \leq n pp≤n
- r e s = r e s + s [ n p ] ⋅ 2 + 1 res = res + s[\frac{n}{p}] \cdot 2 + 1 res=res+s[pn]⋅2+1
- 转换为
g
c
d
(
x
p
,
y
p
)
=
1
x
p
,
y
p
∈
[
1
,
N
p
]
gcd(\frac{x}{p}, \frac{y}{p}) = 1\;\;\frac{x}{p},\frac{y}{p}\in[1,\frac{N}{p}]
gcd(px,py)=1px,py∈[1,pN]
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e7+10;
int primes[N], cnt;
bool st[N];
int phi[N];
LL s[N];
void init(int n)
{
for(int i = 2; i <= n; i++)
{
if(!st[i])
{
primes[++cnt] = i;
phi[i] = i-1;
}
for(int j = 1; primes[j] * i <= n; j++)
{
st[primes[j]*i] = true;
if(i % primes[j] == 0)
{
phi[primes[j]*i] = phi[i] * primes[j];
break;
}
phi[primes[j]*i] = phi[i] * (primes[j] - 1);
}
}
for(int i = 1; i <= n; i++) s[i] = s[i-1] + phi[i];
}
int main()
{
int n;
cin >> n;
init(n);
LL res = 0;
for(int i = 1; i <= cnt; i++)
{
res += s[n/primes[i]] * 2 + 1;
}
cout << res;
return 0;
}