21. Count the Coprimes
β GFG solution to the Count the Coprimes problem: count pairs with GCD=1 using MΓΆbius function and inclusion-exclusion principle for efficient computation. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[] of positive integers. Your task is to count the number of pairs (i, j) such that:
0 β€ i < j β€ n-1gcd(arr[i], arr[j]) = 1
In other words, count the number of unordered pairs of indices (i, j) where the elements at those positions are co-prime (their greatest common divisor is 1).
π Examples
Example 1
Input: arr[] = [1, 2, 3]
Output: 3
Explanation: (0,1), (0,2), (1,2) are the pair of indices where gcd(arr[i], arr[j]) = 1Example 2
Input: arr[] = [4, 8, 3, 9]
Output: 4
Explanation: (0,2), (0,3), (1,2), (1,3) are the pair of indices where gcd(arr[i], arr[j]) = 1π Constraints
$2 \le \text{arr.size()} \le 10^4$
$1 \le \text{arr}[i] \le 10^4$
β
My Approach
The optimal approach uses the MΓΆbius Function with Inclusion-Exclusion Principle to efficiently count coprime pairs without checking every pair individually:
MΓΆbius Function + Inclusion-Exclusion
Core Insight:
Instead of checking all pairs individually (O(nΒ²) with GCD computation), we use number theory.
Count pairs with specific GCD values using inclusion-exclusion principle.
MΓΆbius function helps eliminate overcounting in inclusion-exclusion.
Algorithm Steps:
Step 1: Find maximum element and create frequency array
cnt[].Step 2: Compute MΓΆbius function
mu[]using sieve method.Step 3: For each divisor
d, count how many elements are divisible byd(store indiv[]).Step 4: Apply inclusion-exclusion: pairs with GCD=1 = total pairs - pairs with GCD>1.
Step 5: Use MΓΆbius function to compute the final result efficiently.
MΓΆbius Function Properties:
ΞΌ(1) = 1ΞΌ(n) = 0if n has squared prime factorΞΌ(n) = (-1)^kif n is product of k distinct primesUsed to invert inclusion-exclusion formulas
Mathematical Formula:
For each divisor
d: ifmu[d] β 0anddiv[d] > 1Add
mu[d] * div[d] * (div[d] - 1) / 2to resultThis counts pairs where GCD is exactly 1 using inclusion-exclusion
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the maximum element in array. The first term is for sieve-based MΓΆbius computation, and the second term is for divisor counting across all elements.
Expected Auxiliary Space Complexity: O(n), where n is the maximum element. We need arrays for frequency counting, divisor sums, MΓΆbius function values, and visited markers during sieve computation.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Sieve-Based MΓΆbius with Early Termination
π‘ Algorithm Steps:
Use sieve to compute MΓΆbius function efficiently
Early termination when divisor count < 2
Optimized prime factorization
Single-pass frequency and divisor counting
π Complexity Analysis:
Time: β±οΈ O(n log n)
Auxiliary Space: πΎ O(n) - for arrays
β
Why This Approach?
Sieve-based prime detection
Efficient MΓΆbius computation
Early termination optimizations
π 3οΈβ£ GCD-Based Direct Counting
π‘ Algorithm Steps:
Use inclusion-exclusion principle
Count pairs with specific GCD values
Direct frequency-based computation
Optimized divisor iteration
π Complexity Analysis:
Time: β±οΈ O(n log n)
Auxiliary Space: πΎ O(n) - for frequency arrays
β
Why This Approach?
Direct GCD-based computation
Bottom-up inclusion-exclusion
No MΓΆbius function needed
π 4οΈβ£ Optimized Divisor Sum Approach
π‘ Algorithm Steps:
Precompute smallest prime factors
Fast MΓΆbius function calculation
Efficient divisor counting
Single-pass result computation
π Complexity Analysis:
Time: β±οΈ O(n log log n + n log n)
Auxiliary Space: πΎ O(n) - for SPF and arrays
β
Why This Approach?
SPF-based factorization
On-demand MΓΆbius calculation
Memory-efficient implementation
π 5οΈβ£ Brute Force Approach (For Reference)
π‘ Algorithm Steps:
Check every pair (i, j) where i < j
Compute GCD of arr[i] and arr[j]
Count pairs where GCD equals 1
Simple but inefficient for large inputs
π Complexity Analysis:
Time: β±οΈ O(nΒ² log(max_element))
Auxiliary Space: πΎ O(1)
β
Why This Approach?
Simple and intuitive
Easy to understand and implement
Good for small inputs or educational purposes
Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1010/1120 test cases due to time constraints).
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π Optimized MΓΆbius
π’ O(n log n)
π‘ O(n)
π Fastest for large inputs
πΎ Multiple array allocations
πΊ Sieve-Based MΓΆbius
π’ O(n log n)
π‘ O(n)
π§ Better prime detection
πΎ Additional boolean array
β° GCD-Based Direct
π’ O(n log n)
π‘ O(n)
π No MΓΆbius function needed
π Backward iteration required
π SPF Divisor Sum
π’ O(n log log n + n log n)
π‘ O(n)
β‘ On-demand calculations
π§ Complex factorization logic
π Brute Force (TLE)
π΄ O(nΒ² log(max))
π’ O(1)
π§ Simple to understand
β° Too slow for large inputs
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
β‘ Large arrays, high performance
π₯ Optimized MΓΆbius
β β β β β
π Balanced memory usage
π₯ GCD-Based Direct
β β β β β
π― Educational/interview purposes
π₯ Sieve-Based MΓΆbius
β β β β β
π Competitive programming
π SPF Divisor Sum
β β β β β
π Small inputs, learning
ποΈ Brute Force (TLE)
β β βββ
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated