传送门
Description
A lattice point (x, y) in the first quadrant (x and y are integers greater than or equal to 0), other than the origin, is visible from the origin if the line from (0, 0) to (x, y) does not pass through any other lattice point. For example, the point (4, 2) is not visible since the line from the origin passes through (2, 1). The figure below shows the points (x, y) with 0 ≤ x, y ≤ 5 with lines from the origin to the visible points.
Write a program which, given a value for the size, N, computes the number of visible points (x, y) with 0 ≤ x, y ≤ N.
Input
The first line of input contains a single integer C (1 ≤ C ≤ 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer N (1 ≤ N ≤ 1000), which is the size.
Output
For each dataset, there is to be one line of output consisting of: the dataset number starting at 1, a single space, the size, a single space and the number of visible points for that size.
Sample Input
4
2
4
5
231
Sample Output
1 2 5
2 4 13
3 5 21
4 231 32549
对于这道题题目说要满足原点能够看见就说名与原点的连线之间没有其他的点,也就是那个点坐标的gcd为1
暴力的话就是 ∑ i = 1 n ∑ j = 1 n g c d ( i , j ) \sum_{i=1}^{n}\sum_{j=1}^{n}gcd(i,j) ∑i=1n∑j=1ngcd(i,j)
而对于这个式子我们是可以通过莫比乌斯来化简的,于是有
∑
i
=
1
n
∑
j
=
1
n
g
c
d
(
i
,
j
)
=
∑
i
=
1
n
∑
j
=
1
n
∑
d
∣
g
c
d
(
i
,
j
)
μ
(
d
)
\sum_{i=1}^{n}\sum_{j=1}^{n}gcd(i,j)=\sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{d|gcd(i,j)}\mu(d)
i=1∑nj=1∑ngcd(i,j)=i=1∑nj=1∑nd∣gcd(i,j)∑μ(d)
我们把d提到前面来就有
∑
d
=
1
n
μ
(
d
)
∑
i
=
1
n
/
d
∑
j
=
1
n
/
d
∑
d
=
1
n
μ
(
d
)
∗
⌊
n
d
⌋
∗
⌊
n
d
⌋
\sum_{d=1}^{n}\mu(d)\sum_{i=1}^{n/d}\sum_{j=1}^{n/d}\\~\\ \sum_{d=1}^{n}\mu(d)* \lfloor \frac{n}{d}\rfloor*\lfloor\frac{n}{d}\rfloor
d=1∑nμ(d)i=1∑n/dj=1∑n/d d=1∑nμ(d)∗⌊dn⌋∗⌊dn⌋
然后对这个式子进行一个分块就行了
不过还有一个要注意的地方就是ans要初始化为2,因为坐标轴上还有两个点。
AC代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4;
int miu[maxn];
int vis[maxn];
void mobius(){
for(int i=1;i<=maxn;i++)miu[i]=1;
for(int i=2;i<maxn;i++){
if(!vis[i]){
miu[i]=-1;
for(int j=i+i;j<maxn;j+=i){
vis[j]=1;
if((j/i)%i==0)miu[j]=0;
else miu[j]=-miu[j];
}
}
}
for(int i=1;i<=maxn;i++){
miu[i]+=miu[i-1];
}
}
int main()
{
mobius();
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
int n,r=0,ans=2;
cin>>n;
for(int j=1;j<=n;j=r+1){
r=n/(n/j);
ans+=(miu[r]-miu[j-1])*(n/j)*(n/j);
}
cout<<i<<" "<<n<<" "<<ans<<endl;
}
return 0;
}
本文介绍了一种通过莫比乌斯函数简化计算第一象限中可见格点数量的方法,使用了数学技巧和算法优化,避免了暴力求解,并提供了一个有效的AC代码实现。
531

被折叠的 条评论
为什么被折叠?



