Farey Sequence

Time Limit: 1000MS Memory Limit: 65536K

Description

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.

Sample Input

2
3
4
5
0

Sample Output

1
3
5
9

思路:

题目要求我们求Fi,而每一个F是由前面的F相加然后再加上这个数的符合gcd(a,b) = 1条件的数量,所以用欧拉函数再加上前缀和, 在求欧拉函数的时候可以用质数线性筛,将欧拉数都筛出来。

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const int maxn = 1e+6 + 10;
ll phi[maxn], prime[maxn], sum[maxn];
bool book[maxn] = {false};
void GetPhi() {
    int cnt = 0;
    for (int i = 2; i < maxn; i++) {
        if (!book[i]) {
            phi[i] = i - 1;
            prime[cnt++] = i;
        }
        for (int j = 0; j < cnt && prime[j] * i < maxn; j++) {
            int x = prime[j];
            book[i * x] = true;
            if (i % x == 0) {
                phi[i * x] = phi[i] * x;
                break;
            } else phi[i * x] = phi[i] * phi[x];
        }
    }
    for (int i = 2; i < maxn; i++) {
        sum[i] = sum[i - 1] + phi[i];
    }
}
int main() {
    ios::sync_with_stdio(false);
    GetPhi();
    int n;
    while (~scanf("%d", &n) && n) {
        printf("%lld\n", sum[n]);
    }
    return 0;
}