欧拉φ函数

目录

一,欧拉φ函数

二,函数实现

三,备忘录

四,OJ实战

POJ 3090、ZOJ 2777、UVALive 3571 Visible Lattice Points


一,欧拉φ函数

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

二,函数实现

参考ACM模板

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

三,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.


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;

...

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

void init()
{
	Phi opt;
	for (int i = 1; i <= N; i++)r[i] = opt.getPhi(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,这就得到了递推式。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值