Sum of GCD of Formed Pairs
You are given an integer array nums of length n.
Construct an array prefixGcd where for each index i:
- Let
mxi = max(nums[0], nums[1], ..., nums[i]). prefixGcd[i] = gcd(nums[i], mxi).
After constructing prefixGcd:
- Sort
prefixGcdin non-decreasing order. - Form pairs by taking the smallest unpaired element and the largest unpaired element.
- Repeat this process until no more pairs can be formed.
- For each formed pair, compute the
gcdof the two elements. - If
nis odd, the middle element in theprefixGcdarray remains unpaired and should be ignored.
Return an integer denoting the sum of the GCD values of all formed pairs.
The term gcd(a, b) denotes the greatest common divisor of a and b.
Example 1
Input
nums = [2,6,4]Output
2prefixGcd = [2, 6, 2], which sorts to [2, 2, 6]; the only formed pair has gcd(2, 6) = 2, and the middle element is ignored.Example 2
Input
nums = [3,6,2,8]Output
5prefixGcd = [3, 6, 2, 8], which sorts to [2, 3, 6, 8]; the formed pairs have GCDs gcd(2, 8) = 2 and gcd(3, 6) = 3, so the sum is 5.Constraints
- 1 <= n == nums.length <= 10^5
- 1 <= nums[i] <= 10^9