Skip to main content
Back to problems
Leetcode
Medium
Arrays
Number Theory
Math
Google
Sum of GCD of Formed Pairs

Count all valid formed pairs and sum the GCD of each pair.

Acceptance 0%
Problem Statement

You are given an array of integers. You must form pairs according to the problem’s pairing rule, then compute the greatest common divisor (GCD) for every formed pair and return the total sum of those GCD values.

The key challenge is that the number of possible pairs can be large, so a direct brute-force enumeration may be too slow. A correct solution usually relies on counting how many numbers are divisible by each possible GCD value and combining those counts carefully.

Write a function that returns the sum of GCDs over all formed pairs.

Input Format

  • An integer array nums.
  • The exact pairing rule is determined by the platform problem statement; treat the task as summing GCDs over all valid formed pairs in the given array.

Output Format

  • Return a single integer: the total sum of GCD values over all formed pairs.

Constraints

  • The array may be large enough that an O(n2)O(n^2) pair enumeration is not ideal.
  • Values are positive integers.
  • Use integer arithmetic; the final answer may exceed 32-bit range.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 3, 4]

Output

7

Explanation

The formed pairs are not fully specified here, so this is an illustrative example of summing GCDs over all unordered pairs: gcd(1,2)=1, gcd(1,3)=1, gcd(1,4)=1, gcd(2,3)=1, gcd(2,4)=2, gcd(3,4)=1. The sum is 7.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.