We are given an array of positive integers and an integer k. Find the maximum possible GCD of a sub sequence of size k.
Input : arr = [2, 1, 4, 6] k = 3 Output : 2 GCD of [2, 4, 6] is 2 Input : arr = [1, 2, 3] k = 3 Output : 1 GCD of [1, 2, 3] is 1
Method 1 Generate all the sub sequences of size k one by one and then find the GCD of all such generated sub sequences. Print the largest found GCD.
Method 2 In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element we will calculate its divisors and increment at the index of count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from last index to index 1. If we find an index with value equal to or greater than k, then this means that it is a divisor of at least k elements and also the max GCD.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Smallest subsequence having GCD equal to GCD of given array
- Minimum LCM and GCD possible among all possible sub-arrays
- Longest subsequence having maximum GCD between any pair of distinct elements
- Pair of integers having least GCD among all given pairs having GCD exceeding K
- Maximum possible GCD after replacing at most one element in the given array
- Maximum possible GCD for a pair of integers with product N
- Maximum possible GCD for a pair of integers with sum N
- Maximum length subsequence such that adjacent elements in the subsequence have a common factor
- Largest subsequence having GCD greater than 1
- Subsequence X of length K such that gcd(X, X) + (X, X) + ... is maximized
- Minimum length of subsequence having unit GCD
- Maximum product of an increasing subsequence of size 3
- Maximum product of subsequence of size k
- Maximum product of bitonic subsequence of size 3
- Subsequence with maximum pairwise absolute difference and minimum size
- Maximum product of a triplet (subsequence of size 3) in array
- Maximum subsequence sum possible by multiplying each element by its index
- Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence
- GCD of all subarrays of size K
- Maximum XOR value of maximum and second maximum element among all possible subarrays
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.