题目链接:https://vjudge.net/problem/POJ-3090
题目大意:
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.
分析:
首先发现假如(a,b)为一个lattice point,则(ka,kb)必然不是lattice point
因为二者在一条直线上
故可得:
坐标中任意一点(a,b),若a,b有共同因子则其不是lattice point,若互质则其为lattice point
特殊点:(0,1)和(1,0)为lattice point
现在让从1开始考虑:
坐标含1的3个点:(0,1)、(1,1)、(1,0)都是,所以ans[1]=3
坐标含2的5个点:(x,2)或(2,x)中只要有一个为lattice point另一个必然也是,发现只有x=1满足条件,所以ans[2]=ans[1]+2=5
坐标含3的7个点:推出x为1或2都可以,所以ans[3]=ans[2]+4=9
综上:
ans[1]=3;
ans[x]=ans[x-1]+φ(x)
该式可用于递推求解,此题得解
其中φ(x)为1~x中与x互质的数,即欧拉函数值;
欧拉函数打表方法可见:欧拉函数打表
代码
#include <cstdio>
#include <string.h>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int phi[1005];
int ans[1005];
void Euler_excel(){
phi[1]=1;
for(int i=2;i<=1000;i++) phi[i]=0;
for(int i=2;i<=1000;i++){
if(!phi[i]){
for(int j=i;j<=1000;j+=i){
if(!phi[j]) phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
}
}
void pre_sum(){
ans[1]=3;
for(int i=2;i<=1000;i++)
ans[i]=2*phi[i]+ans[i-1];
}
int main()
{
Euler_excel();
pre_sum();
int C;
scanf("%d",&C);
for(int i=1;i<=C;i++){
int N;
scanf("%d",&N);
printf("%d %d %d\n",i,N,ans[N]);
}
return 0;
}