PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SP0000257. Bài học về sàng số nguyên tố đầu tiên (The First Lesson on the Sieve of Eratosthenes)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Bài học về sàng số nguyên tố đầu tiên (The First Lesson on the Sieve of Eratosthenes)

The First Lesson on the Sieve of Eratosthenes

Source: VNOJ

Version: Phuoc Hung OJ Extended

Problem Statement

Consider the following sieve procedure, given an integer nn and an array aa containing integers between 22 and nn:

  • Initially mark every integer 2,3,…,n2,3,\ldots,n as not removed, and start with an empty output list.
  • Process values vv in their exact order in aa. If vv has already been removed, skip it.
  • Otherwise append vv to the output list, then mark all multiples strictly greater than vv, namely 2v,3v,…,⌊n/v⌋v2v,3v,\ldots,\lfloor n/v\rfloor v, as removed.

You are given a permutation a1,a2,…,an−1a_1,a_2,\ldots,a_{n-1} of the integers 2,3,…,n2,3,\ldots,n. In an arbitrary order, this sieve may append composite numbers.

You may perform the following operation any number of times: swap two adjacent elements, provided exactly one is prime and the other is composite. Swapping two primes or two composites is forbidden.

Find the minimum number of swaps needed so that running the sieve on the resulting array appends only primes. A valid sequence of swaps is guaranteed to exist.

Input

The first line contains the sieve limit nn.

The second line contains exactly n−1n-1 integers a1,a2,…,an−1a_1,a_2,\ldots,a_{n-1}, a permutation of 2,3,…,n2,3,\ldots,n.

Output

Print a single 64-bit integer: the minimum number of allowed adjacent swaps so that the sieve output contains no composite number.

Subtasks

  • Subtask 1 (50 points): 2≤n≤50002\le n\le 5000; 2≤ai≤n2\le a_i\le n for every 1≤i≤n−11\le i\le n-1; all aia_i are pairwise distinct.
  • Subtask 2 (50 points): 2≤n≤1062\le n\le 10^6; 2≤ai≤n2\le a_i\le n for every 1≤i≤n−11\le i\le n-1; all aia_i are pairwise distinct.

Examples

Input

8
7 6 2 3 4 5 8

Output

1

Explanation

For n=8n=8, the original permutation is [7,6,2,3,4,5,8][7,6,2,3,4,5,8].

If the sieve is run immediately, 77 is appended, followed by composite 66 because none of its prime divisors appeared earlier. Thus zero swaps cannot be sufficient.

Swap the adjacent composite 66 and prime 22 once, obtaining [7,2,6,3,4,5,8][7,2,6,3,4,5,8]. When 22 is processed, it removes 4,6,84,6,8; thus 66 is skipped. The resulting sieve output is [7,2,3,5][7,2,3,5], containing primes only.

At least one swap is necessary and one is sufficient, so the answer is 11.