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

#GL0000365. Tối đa hóa tổng GCD tiền tố – Bản khó (Divan and Kostomuksha (Hard))

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tối đa hóa tổng GCD tiền tố – Bản khó (Divan and Kostomuksha (Hard))

Divan and Kostomuksha (Hard)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an array of nn positive integers. You may reorder every element arbitrarily. For any resulting order, define the ii-th prefix GCD by

gi=gcd⁡(a1,a2,…,ai).g_i=\gcd(a_1,a_2,\ldots,a_i).

Maximize ∑i=1ngi\sum_{i=1}^n g_i.

Hard version: elements can be as large as 2⋅1072\cdot10^7, so visiting all pairs of multiples as in the easy version may be too slow. The intended optimization combines a prime sieve with divisibility DP.

Input

  • Line 1: nn.
  • Line 2: nn integers aia_i.

Output

Print the maximum prefix-GCD sum using a 64-bit integer type.

Subtasks

  • Subtask 1 (20 points): 1<=n<=8;1<=ai<=301 <= n <= 8; 1 <= a_i <= 30.
  • Subtask 2 (30 points): 1<=n<=1000;1<=ai<=50000001 <= n <= 1000; 1 <= a_i <= 5000000.
  • Subtask 3 (50 points): 1<=n<=100000;1<=ai<=200000001 <= n <= 100000; 1 <= a_i <= 20000000.

Examples

Example 1

Input

6
2 3 1 2 6 2

Output

14

Explanation

Both versions optimize the same prefix-gcd sum. The order [6,2,2,2,3,1] gives 14.

Example 2

Input

10
5 7 10 3 1 10 100 3 42 54

Output

131

Explanation

The order [100,10,10,5,1,3,3,7,42,54] yields 131.