欧拉函数如何打表?

1.题目引入:

The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rational numbers a/b with 0 < a < b <= n and gcd(a,b) = 1 arranged in increasing order. The first few are 
F2 = {1/2} 
F3 = {1/3, 1/2, 2/3} 
F4 = {1/4, 1/3, 1/2, 2/3, 3/4} 
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5} 

You task is to calculate the number of terms in the Farey sequence Fn.

Input

There are several test cases. Each test case has only one line, which contains a positive integer n (2 <= n <= 106). There are no blank lines between cases. A line with a single 0 terminates the input.

Output

For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey sequence Fn. 

2.样例输出: 

Sample Input

2
3
4
5
0

Sample Output

1
3
5
9

题目大意:寻找N(包括 N )以内互质的数将他们组成一个真分数,现在需要我们求他们最多组成的个数,这里就需要用到我们的欧拉打表,为何?

我们发现每次新增的数都是以 i 为分母和它的相对质数为分子建立的数, 因此每次的总的分数为上一次的值加上新增的欧拉函数。

3.代码如下: 

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1000100;
ll e[N];
void init()
{
	for (int i = 0; i < N; i++) e[i] = i;
	for (ll i = 2; i < N; i++)
	{
		if (e[i] == i)			//如果该数还等于原值则还没有被作为质因子
		{
			for (ll j = i; j < N; j += i)
			{
				e[j] = e[j] / i * (i - 1);   //寻找每个数的欧拉函数即每次减去以 i 为质因子的所有小于 N 的数
				//e 0x0079c138 {0, 1, 1, 3, 2, 5, 3, 7, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, ...}
				//这是运行数次之后的e值 可以发现他们都减去了 以 i 为质因子的小于 e[j] 的数 以 e[6]=5-2(2和4)=3;
			}

		}
	}
	for (int i = 3; i < N; i++) e[i] += e[i - 1];   
	// 我们发现每次新增的数都是以 i 为分母和它的相对质数为分子建立的数
	// 因此每次的总 分数为上一次的值加上新增的欧拉函数
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	ll n;
	init();
	while (cin >> n && n)
	{
		cout << e[n] << "\n";
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风遥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值