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.
C++
// Simple C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include<bits/stdc++.h>
using namespace std;
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
int ans = 0;
// Finding the Maximum value in arr[]
int maxele = *max_element(arr, arr+n);
// Iterate from 2 to maximum possible
// divisor of all give values
for (int i=2; i<=maxele; ++i)
{
int count = 0;
for (int j=0; j<n; ++j)
{
// If we found divisor,
// increment count
if (arr[j]%i == 0)
++count;
}
ans = max(ans, count);
}
return ans;
}
// Driver code
int main()
{
int arr[] = {3, 6, 2, 5, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << largestGCDSubsequence(arr, size);
return 0;
}
Java
// Efficient Java program to find length of
// the largest subsequence with GCD greater
// than 1.
import java.util.Arrays;
class GFG {
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int arr[], int n)
{
int ans = 0;
// Finding the Maximum value in arr[]
int maxele = Arrays.stream(arr).max().getAsInt();;
// Iterate from 2 to maximum possible
// divisor of all give values
for (int i=2; i<=maxele; ++i)
{
int count = 0;
for (int j=0; j<n; ++j)
{
// If we found divisor,
// increment count
if (arr[j]%i == 0)
++count;
}
ans = Math.max(ans, count);
}
return ans;
}
// Driver program to test above
public static void main(String[] args) {
int arr[] = {3, 6, 2, 5, 4};
int size = arr.length;
System.out.println(largestGCDSubsequence(arr, size));
}
}
//this code contributed by Rajput-Ji
Python3
# Simple Python 3 program to find length of
# the largest subsequence with GCD greater
# than 1.
# Returns length of the largest subsequence
# with GCD more than 1.
def largestGCDSubsequence(arr, n):
ans = 0
# Finding the Maximum value in arr[]
maxele = max(arr)
# Iterate from 2 to maximum possible
# divisor of all give values
for i in range(2, maxele + 1):
count = 0
for j in range(n):
# If we found divisor,
# increment count
if (arr[j] % i == 0):
count += 1
ans = max(ans, count)
return ans
# Driver code
if __name__ == '__main__':
arr = [3, 6, 2, 5, 4]
size = len(arr)
print(largestGCDSubsequence(arr, size))
# This code is contributed by Rajput-Ji
C#
// Efficient C# program to find length of
// the largest subsequence with GCD greater
// than 1.
using System;
using System.Linq;
public class GFG {
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int []arr, int n)
{
int ans = 0;
// Finding the Maximum value in arr[]
int maxele = arr.Max();
// Iterate from 2 to maximum possible
// divisor of all give values
for (int i=2; i<=maxele; ++i)
{
int count = 0;
for (int j=0; j<n; ++j)
{
// If we found divisor,
// increment count
if (arr[j]%i == 0)
++count;
}
ans = Math.Max(ans, count);
}
return ans;
}
// Driver program to test above
public static void Main() {
int []arr = {3, 6, 2, 5, 4};
int size = arr.Length;
Console.Write(largestGCDSubsequence(arr, size));
}
}
//this code contributed by Rajput-Ji
PHP
<?php
// Simple PHP program to find length of
// the largest subsequence with GCD greater
// than 1.
// Returns length of the largest subsequence
// with GCD more than 1.
function largestGCDSubsequence($arr, $n)
{
$ans = 0;
// Finding the Maximum value in arr[]
$maxele = max($arr);
// Iterate from 2 to maximum possible
// divisor of all give values
for ($i = 2; $i <= $maxele; ++$i)
{
$count = 0;
for ($j = 0; $j < $n; ++$j)
{
// If we found divisor,
// increment count
if ($arr[$j] % $i == 0)
++$count;
}
$ans = max($ans, $count);
}
return $ans;
}
// Driver code
$arr = array(3, 6, 2, 5, 4);
$size = count($arr);
echo largestGCDSubsequence($arr, $size);
// This code is contributed by mits
?>
JavaScript
<script>
// Efficient javascript program to find length of
// the largest subsequence with GCD greater
// than 1.
// Returns length of the largest subsequence
// with GCD more than 1.
function largestGCDSubsequence(arr , n)
{
var ans = 0;
// Finding the Maximum value in arr
var maxele =Math.max(...arr);
// Iterate from 2 to maximum possible
// divisor of all give values
for ( var i = 2; i <= maxele; ++i)
{
var count = 0;
for (j = 0; j < n; ++j)
{
// If we found divisor,
// increment count
if (arr[j] % i == 0)
++count;
}
ans = Math.max(ans, count);
}
return ans;
}
// Driver program to test above
var arr = [ 3, 6, 2, 5, 4 ];
var size = arr.length;
document.write(largestGCDSubsequence(arr, size));
// This code is contributed by aashish1995
</script>
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.
C++
// Efficient C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include<bits/stdc++.h>
using namespace std;
#define MAX 100001
// prime[] for storing smallest prime divisor of element
// count[] for storing the number of times a particular
// divisor occurs in a subsequence
int prime[MAX], countdiv[MAX];
// Simple sieve to find smallest prime factors of numbers
// smaller than MAX
void SieveOfEratosthenes()
{
for (int i = 2; i * i <= MAX; ++i)
{
if (!prime[i])
for (int j = i * 2; j <= MAX; j += i)
prime[j] = i;
}
// Prime number will have same divisor
for (int i = 1; i < MAX; ++i)
if (!prime[i])
prime[i] = i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
int ans = 0;
for (int i=0; i < n; ++i)
{
int element = arr[i];
// Fetch total unique prime divisor of element
while (element > 1)
{
int div = prime[element];
// Increment count[] of Every unique divisor
// we get till now
++countdiv[div];
// Find maximum frequency of divisor
ans = max(ans, countdiv[div]);
while (element % div==0)
element /= div;
}
}
return ans;
}
// Driver code
int main()
{
// Pre-compute smallest divisor of all numbers
SieveOfEratosthenes();
int arr[] = {10, 15, 7, 25, 9, 35};
int size = sizeof(arr) / sizeof(arr[0]);
cout << largestGCDSubsequence(arr, size);
return 0;
}
Java
// Efficient Java program to find length of
// the largest subsequence with GCD greater
// than 1.
class GFG
{
static int MAX = 100001;
// prime[] for storing smallest prime divisor
// of element count[] for storing the number
// of times a particular divisor occurs
// in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
// Simple sieve to find smallest prime
// factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
for (int i = 2; i * i <= MAX; ++i)
{
if (prime[i] == 0)
for (int j = i * 2; j <= MAX; j += i)
prime[j] = i;
}
// Prime number will have same divisor
for (int i = 1; i < MAX; ++i)
if (prime[i] == 0)
prime[i] = i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int arr[], int n)
{
int ans = 0;
for (int i = 0; i < n; ++i)
{
int element = arr[i];
// Fetch total unique prime divisor of element
while (element > 1)
{
int div = prime[element];
// Increment count[] of Every unique divisor
// we get till now
++countdiv[div];
// Find maximum frequency of divisor
ans = Math.max(ans, countdiv[div]);
while (element % div == 0)
element /= div;
}
}
return ans;
}
// Driver code
public static void main (String[] args)
{
// Pre-compute smallest divisor of all numbers
SieveOfEratosthenes();
int arr[] = {10, 15, 7, 25, 9, 35};
int size = arr.length;
System.out.println(largestGCDSubsequence(arr, size));
}
}
// This code is contributed by mits
Python3
# Efficient Python3 program to find length
# of the largest subsequence with GCD
# greater than 1.
import math as mt
MAX = 100001
# prime[] for storing smallest
# prime divisor of element
# count[] for storing the number
# of times a particular divisor
# occurs in a subsequence
prime = [0 for i in range(MAX + 1)]
countdiv = [0 for i in range(MAX + 1)]
# Simple sieve to find smallest prime
# factors of numbers smaller than MAX
def SieveOfEratosthenes():
for i in range(2, mt.ceil(mt.sqrt(MAX + 1))):
if (prime[i] == 0):
for j in range(i * 2, MAX + 1, i):
prime[j] = i
# Prime number will have same divisor
for i in range(1, MAX):
if (prime[i] == 0):
prime[i] = i
# Returns length of the largest
# subsequence with GCD more than 1.
def largestGCDSubsequence(arr, n):
ans = 0
for i in range(n):
element = arr[i]
# Fetch total unique prime
# divisor of element
while (element > 1):
div = prime[element]
# Increment count[] of Every
# unique divisor we get till now
countdiv[div] += 1
# Find maximum frequency of divisor
ans = max(ans, countdiv[div])
while (element % div == 0):
element = element // div
return ans
# Driver code
# Pre-compute smallest divisor
# of all numbers
SieveOfEratosthenes()
arr= [10, 15, 7, 25, 9, 35]
size = len(arr)
print(largestGCDSubsequence(arr, size))
# This code is contributed
# by Mohit kumar 29
C#
// Efficient C# program to find length of
// the largest subsequence with GCD greater
// than 1.
using System;
class GFG
{
static int MAX=100001;
// prime[] for storing smallest
// prime divisor of element count[]
// for storing the number of times
// a particular divisor occurs in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
// Simple sieve to find smallest prime
// factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
for (int i = 2; i * i <= MAX; ++i)
{
if (prime[i] == 0)
for (int j = i * 2; j <= MAX; j += i)
prime[j] = i;
}
// Prime number will have same divisor
for (int i = 1; i < MAX; ++i)
if (prime[i] == 0)
prime[i] = i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int []arr, int n)
{
int ans = 0;
for (int i = 0; i < n; ++i)
{
int element = arr[i];
// Fetch total unique prime divisor of element
while (element > 1)
{
int div = prime[element];
// Increment count[] of Every unique divisor
// we get till now
++countdiv[div];
// Find maximum frequency of divisor
ans = Math.Max(ans, countdiv[div]);
while (element % div==0)
element /= div;
}
}
return ans;
}
// Driver code
public static void Main()
{
// Pre-compute smallest
// divisor of all numbers
SieveOfEratosthenes();
int []arr = {10, 15, 7, 25, 9, 35};
int size = arr.Length;
Console.WriteLine(largestGCDSubsequence(arr, size));
}
}
// This code is contributed by mits
PHP
<?php
// Efficient PHP program to find length of
// the largest subsequence with GCD greater
// than 1.
$MAX = 10001;
// prime[] for storing smallest prime divisor of element
// count[] for storing the number of times a particular
// divisor occurs in a subsequence
$prime = array_fill(0, $MAX, 0);
$countdiv = array_fill(0, $MAX, 0);
// Simple sieve to find smallest prime factors of numbers
// smaller than MAX
function SieveOfEratosthenes()
{
global $MAX,$prime;
for ($i = 2; $i * $i <= $MAX; ++$i)
{
if ($prime[$i] == 0)
for ($j = $i * 2; $j <= $MAX; $j += $i)
$prime[$j] = $i;
}
// Prime number will have same divisor
for ($i = 1; $i < $MAX; ++$i)
if ($prime[$i] == 0)
$prime[$i] = $i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
function largestGCDSubsequence($arr, $n)
{
global $countdiv,$prime;
$ans = 0;
for ($i = 0; $i < $n; ++$i)
{
$element = $arr[$i];
// Fetch total unique prime divisor of element
while ($element > 1)
{
$div = $prime[$element];
// Increment count[] of Every unique divisor
// we get till now
++$countdiv[$div];
// Find maximum frequency of divisor
$ans = max($ans, $countdiv[$div]);
while ($element % $div == 0)
$element = (int)($element/$div);
}
}
return $ans;
}
// Driver code
// Pre-compute smallest divisor of all numbers
SieveOfEratosthenes();
$arr = array(10, 15, 7, 25, 9, 35);
$size = count($arr);
echo largestGCDSubsequence($arr, $size);
// This code is contributed by mits
?>
JavaScript
<script>
// Efficient Javascript program to find length of
// the largest subsequence with GCD greater
// than 1.
let MAX = 100001;
// prime[] for storing smallest prime divisor
// of element count[] for storing the number
// of times a particular divisor occurs
// in a subsequence
let prime = new Array(MAX + 1);
let countdiv = new Array(MAX + 1);
for(let i=0;i<MAX+1;i++)
{
prime[i]=0;
countdiv[i]=0;
}
// Simple sieve to find smallest prime
// factors of numbers smaller than MAX
function SieveOfEratosthenes()
{
for (let i = 2; i * i <= MAX; ++i)
{
if (prime[i] == 0)
for (let j = i * 2; j <= MAX; j += i)
prime[j] = i;
}
// Prime number will have same divisor
for (let i = 1; i < MAX; ++i)
if (prime[i] == 0)
prime[i] = i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
function largestGCDSubsequence(arr,n)
{
let ans = 0;
for (let i = 0; i < n; ++i)
{
let element = arr[i];
// Fetch total unique prime divisor of element
while (element > 1)
{
let div = prime[element];
// Increment count[] of Every unique divisor
// we get till now
++countdiv[div];
// Find maximum frequency of divisor
ans = Math.max(ans, countdiv[div]);
while (element % div == 0)
element /= div;
}
}
return ans;
}
// Driver code
// Pre-compute smallest divisor of all numbers
SieveOfEratosthenes();
let arr=[10, 15, 7, 25, 9, 35];
let size = arr.length;
document.write(largestGCDSubsequence(arr, size));
// This code is contributed by unknown2108
</script>
Output:
4
Time complexity: O( n*log(max(arr[i])) ) + MAX*log(log(MAX))
Auxiliary space: O(MAX)
Similar Reads
GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers.GCD of Two NumbersFastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The E
4 min read
Program to Find GCD or HCF of Two Numbers
Given two numbers a and b, the task is to find the GCD of the two numbers.Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples:Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4, 5, 10 an
15+ min read
Check if two numbers are co-prime or not
Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : Input : 2 3Output : Co-PrimeInput : 4 8Output : Not Co-PrimeThe idea is simple, we find GCD of two numbers a
5 min read
GCD of more than two (or array) numbers
Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
11 min read
Program to find LCM of two numbers
LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 12, b = 18Output : 3636 is the smallest number divisible by both 12 and 18Input : a = 5, b = 11Output : 5555 is the smallest number divisible by both 5 and 11[Naive Approach] Using Conditional Loop This appro
8 min read
LCM of given array elements
In this article, we will learn how to find the LCM of given array elements.Given an array of n numbers, find the LCM of it. Example:Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
14 min read
Find the other number when LCM and HCF given
Given a number A and L.C.M and H.C.F. The task is to determine the other number B. Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula: A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60
4 min read
Minimum insertions to make a Co-prime array
Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, gcd(a, b) = 1 . Examples : Input : A[] = {2, 7, 28}Output : 1Exp
6 min read
Find the minimum possible health of the winning player
Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winn
4 min read
Minimum squares to evenly cut a rectangle
Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not min
4 min read