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 0Sample 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; }