VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-subsequence-gcd-greater-1/

⇱ Largest subsequence having GCD greater than 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest subsequence having GCD greater than 1

Last Updated : 13 Sep, 2023

Given an array, arr[], find the largest subsequence such that GCD of all those subsequences are greater than 1. 
Examples: 
 

Input: 3, 6, 2, 5, 4
Output: 3
Explanation: There are only three elements(6, 
2, 4) having GCD greater than 1 i.e., 2. So the 
largest subsequence will be 3

Input: 10, 15, 7, 25, 9, 35
Output: 4


 


 

Naive Approach(Method 1)


Simple approach is to generate all the subsequence one by one and then find the GCD of all such generated set. Problem of this approach is that it grows exponentially in 2N
 

Iterative Approach(Method 2)


If we observe then we will found that to make gcd greater than 1, all such elements must contain common factor greater than 1 which evenly divides all these values. So in order to get that factor we will iterate from 2 to Maximum element of array and then check for divisibility. 
 

Output: 
 

3


Time Complexity: O(n * max(arr[i])) where n is size of array. 
Auxiliary Space: O(1)
 

Best Approach(Method 3)


An efficient approach is to use prime factorization method with the help of Sieve of Eratosthenes. First of all we will find the smallest prime divisor of all elements by pre-computed sieve. After that we will mark all the prime divisor of every element of arr[] by factorizing it with the help of pre-computed prime[] array. 
Now we have all the marked primes occurring in all the array elements. The last step is to find the maximum count of all such prime factors. 
 

Output: 
 

 4


Time complexity: O( n*log(max(arr[i])) ) + MAX*log(log(MAX)) 
Auxiliary space: O(MAX)
 

Comment
Article Tags: