目录

​一,欧拉φ函数​

​二,函数实现​

​三,备忘录​

​四,OJ实战​

​POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points​


一,欧拉φ函数

对正整数n,欧拉函数是小于或等于n的正整数中与n互质的数的数目。

二,函数实现

int phi(int n)
{
int r = n;
for (int i = 2; i*i <= n; i++)
{
if (n%i == 0)
{
while (n%i == 0)n /= i;
r = r / i*(i - 1);
}
}
if (n > 1)r = r / n*(n - 1);
return r;
}

时间复杂度:O(sqrt(n))

三,备忘录

如果phi函数可能会多次调用,那就存备忘录

const int N=1000;
int r[N+1];

void init()
{
for(int i=1;i<=N;i++)r[i]=phi(i);
}

四,OJ实战

POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points

题目:

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.

欧拉φ函数POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice 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


题意:

找出从原点出发有多少线段不经过其他点。

思路一:

从(0,0)到(x,y)的线段不经过其他点其实就是(x,y)=1

所以本题答案是2S+1,其中S=φ(1)+φ(2)+......+φ(n)

代码:

#include<iostream>
using namespace std;

int phi(int n)
{
int r = n;
for (int i = 2; i*i <= n; i++)
{
if (n%i == 0)
{
while (n%i == 0)n /= i;
r = r / i*(i - 1);
}
}
if (n > 1)r = r / n*(n - 1);
return r;
}

const int N=1000;
int r[N+1];

void init()
{
for(int i=1;i<=N;i++)r[i]=phi(i);
}

int main() {
init();
for(int i=1;i<=N;i++)r[i]+=r[i-1];
int t, n;
cin >> t;
for (int cas = 1; cas <= t; cas++) {
cin >> n;
cout << cas << " " << n << " " << r[n]*2 + 1 << endl;
}
return 0;
}

思路二:

递推,代码:

#include<iostream>
#include<stdio.h>
using namespace std;

int r[1001];

int main()
{
r[1] = 1;
for (int i = 2; i <= 1000; i++)
{
r[i] = i*i;
for (int j = 2; j <= i; j++)r[i] -= r[i / j];
}
int t, n;
cin >> t;
for (int cas = 1; cas <= t; cas++)
{
cin >> n;
cout << cas << " " << n << " " << r[n] + 2 << endl;
}
return 0;
}

代码很简洁而且非常高效,16ms AC

这个递推式是什么原理呢?

首先解释一下,这个r不是答案,r+2才是答案,也就是说,

我没有计算x=0或者y=0的情况,也就是没有计算(0,1)和(1,0)这2个点。

然后怎么算r呢?

枚举gcd(x,y)

gcd(x,y)=1的情况有r[n]种,gcd(x,y)=2的情况有r[n/2]种

gcd(x,y)=3的情况有r[n/3]种......

所有的加起来,一共是n*n,这就得到了递推式。