Counting Coprime Pairs

medium number-theory math prefix-sums combinatorics 2000 ms · 512 MB

Counting Coprime Pairs

For a positive integer n, consider every ordered pair (i, j) with 1 ≤ i ≤ n and 1 ≤ j ≤ n. Call the pair coprime if gcd(i, j) = 1, that is, i and j share no common factor other than 1. Note that i and j may be equal (and (1, 1) is coprime, since gcd(1, 1) = 1), and that (i, j) and (j, i) are counted separately whenever i ≠ j.

You are given q independent queries. Each query gives a value n, and you must report how many coprime ordered pairs (i, j) satisfy 1 ≤ i, j ≤ n.

Input

The first line contains an integer q (1 ≤ q ≤ 10^5), the number of queries.

The second line contains q integers n_1, n_2, ..., n_q (1 ≤ n_i ≤ 10^7), one per query.

Output

Print q lines. The k-th line must contain a single integer: the number of coprime ordered pairs (i, j) with 1 ≤ i, j ≤ n_k.

The answer can be large (on the order of 10^14), so use a 64-bit integer type.

Notes

In the first example, for n = 1 the only pair is (1, 1), which is coprime, so the answer is 1. For n = 2 the pairs are (1,1), (1,2), (2,1), (2,2); all but (2,2) are coprime, so the answer is 3. For n = 3 there are 9 pairs in total, and only (2,2) and (3,3) fail to be coprime, giving 7.

Checking every one of the n^2 pairs per query is far too slow once n and q are both large: a solution should instead precompute, once, enough information to answer each query in O(1).

Example 1

Input

3
1 2 3

Output

1
3
7

Example 2

Input

2
5 10

Output

19
63

Hints · reveal one at a time if you're stuck

Hint 1

Pairs with i equal to j are almost never coprime, so most of the count comes from pairs with different values. For a fixed j, how many smaller positive integers are coprime to j, and does that count depend on anything besides j?

Hint 2

Each value j contributes a per-j count, and the answer for n sums those contributions over all j up to n, with the symmetry of ordered pairs accounted for. Since there are many queries, precompute the per-j values for all j up to the largest n once.

Hint 3

A linear sieve that records each number's smallest prime factor can produce the per-j counts for all values up to 10^7 in linear time, and a prefix sum then answers each query with one lookup. Keep the sums in 64-bit integers.

report an issue Prefer your own editor? sooks prep 80 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.