Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Summation of GCD of all the pairs up to n
Next article icon

Largest Subset with GCD 1

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given n integers, we need to find size of the largest subset with GCD equal to 1. 
Input Constraint : n <= 10^5, A[i] <= 10^5

Examples: 

Input : A = {2, 3, 5}
Output : 3
Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.

Input : A = {3, 18, 12}
Output : -1
Explanation: No subset of the array has a GCD greater than 1, so the output is -1.

[Naive Approach] by Evaluating All Subsets - O(n * log(n) * 2^n) Time and O(n) Space

We find GCD of all possible subsets and find the largest subset whose GCD is 1. Total time taken will be equal to the time taken to evaluate GCD of all possible subsets. Total possible subsets are 2n. In worst case there are n elements in subset and time taken to calculate its GCD will be n * log(n) 
Extra space required to hold current subset is O(n) 

[Expected Approach] By Checking GCD of Complete Set - O(n* log(n)) Time and O(1) Space

Let say we find a subset with GCD 1, if we add a new element to it then GCD still remains 1. Hence if a subset exists with GCD 1 then GCD of the complete set is also 1. Hence we first find GCD of the complete set, if its 1 then complete set is that subset else no subset exist with GCD 1. 
 

C++
// C++ program to find size of the largest subset with GCD 1 #include <iostream> using namespace std;  // Function to return gcd of a and b int gcd(int a, int b) {     if (a == 0)         return b;     return gcd(b%a, a); }  // Function to find largest subset with GCD 1 int largestGCD1Subset(int A[], int n) {     // finding gcd of whole array     int currentGCD = A[0];     for (int i=1; i<n; i++)     {         currentGCD = gcd(currentGCD, A[i]);          // If current GCD becomes 1 at any moment,         // then whole array has GCD 1.         if (currentGCD == 1)             return n;     }      return 0; }  // Driver program to test above function int main() {     int A[] = {2, 18, 6, 3};     int n = sizeof(A)/sizeof(A[0]);     cout << largestGCD1Subset(A, n);     return 0; } 
Java
// Java program to find size of the // largest subset with GCD 1 import java.io.*;  class GFG {          // Function to return gcd of     // a and b     static int gcd(int a, int b)     {         if (a == 0)             return b;         return gcd(b % a, a);     }      // Function to find largest     // subset with GCD 1     static int largestGCD1Subset(int A[],                                    int n)     {                  // finding gcd of whole array         int currentGCD = A[0];                  for (int i=1; i<n; i++)         {             currentGCD =                      gcd(currentGCD, A[i]);                  // If current GCD becomes 1             // at any moment, then whole             // array has GCD 1.             if (currentGCD == 1)                 return n;         }              return 0;     }          // Driver code     public static void main (String[] args)     {         int A[] = {2, 18, 6, 3};         int n =A.length;                  System.out.println(                   largestGCD1Subset(A, n) );     } }  // This code is contributed by Sam007. 
Python
# python program to find size of the # largest subset with GCD 1  # Function to return gcd of a and b def gcd( a, b):          if (a == 0):         return b              return gcd(b%a, a)   # Function to find largest subset # with GCD 1 def largestGCD1Subset(A, n):          # finding gcd of whole array     currentGCD = A[0];     for i in range(1, n):                  currentGCD = gcd(currentGCD, A[i])          # If current GCD becomes 1 at         # any moment, then whole          # array has GCD 1.         if (currentGCD == 1):             return n     return 0  # Driver code A = [2, 18, 6, 3] n = len(A) print (largestGCD1Subset(A, n))  # This code is Contributed by Sam007. 
C#
// C# program to find size of the // largest subset with GCD 1 using System;          public class GFG {          // Function to return gcd of     // a and b     static int gcd(int a, int b)     {         if (a == 0)             return b;         return gcd(b % a, a);     }      // Function to find largest subset     // with GCD 1     static int largestGCD1Subset(int []A,                                    int n)     {                  // finding gcd of whole array         int currentGCD = A[0];         for (int i = 1; i < n; i++)         {             currentGCD =                      gcd(currentGCD, A[i]);                  // If current GCD becomes 1 at             // any moment, then whole             // array has GCD 1.             if (currentGCD == 1)                 return n;         }              return 0;     }          // Driver method      public static void Main()     {         int []A = {2, 18, 6, 3};         int n = A.Length;                  Console.Write(               largestGCD1Subset(A, n));     } }  // This code is contributed by Sam007. 
JavaScript
<script>  // Javascript program to find size of the // largest subset with GCD 1  // Function to return gcd of a and b function gcd(a, b) {     if (a == 0)         return b;     return gcd(b % a, a); }  // Function to find largest subset // with GCD 1 function largestGCD1Subset(A, n) {          // finding gcd of whole array     let currentGCD = A[0];     for ( let i = 1; i < n; i++)     {         currentGCD =             gcd(currentGCD, A[i]);          // If current GCD becomes 1          // at any moment, then          // whole array has GCD 1.         if (currentGCD == 1)             return n;     }      return 0; }  // Driver program let A = [2, 18, 6, 3]; let n = A.length; document.write(largestGCD1Subset(A, n));      // This code is contributed by _saurabh_jaiswal  </script> 
PHP
<?php  // php program to find size of the // largest subset with GCD 1  // Function to return gcd of a and b function gcd($a, $b) {     if ($a == 0)         return $b;     return gcd($b % $a, $a); }  // Function to find largest subset // with GCD 1 function largestGCD1Subset($A, $n) {          // finding gcd of whole array     $currentGCD = $A[0];     for ( $i = 1; $i < $n; $i++)     {         $currentGCD =             gcd($currentGCD, $A[$i]);          // If current GCD becomes 1          // at any moment, then          // whole array has GCD 1.         if ($currentGCD == 1)             return $n;     }      return 0; }  // Driver program $A = array(2, 18, 6, 3); $n = sizeof($A); echo largestGCD1Subset($A, $n);      // This code is contributed by ajit  ?> 

Output
4

Time Complexity : O(n* log(n))
Space Complexity : O(1)
 


Next Article
Summation of GCD of all the pairs up to n

P

Pratik Chhajer
Improve
Article Tags :
  • Mathematical
  • DSA
  • Basic Coding Problems
  • GCD-LCM
Practice Tags :
  • Mathematical

Similar Reads

    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
    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
    Euler's Totient Function
    Given an integer n, find the value of Euler's Totient Function, denoted as Φ(n). The function Φ(n) represents the count of positive integers less than or equal to n that are relatively prime to n. Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are re
    10 min read
    Euclidean algorithms (Basic and Extended)
    The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.Examples:input: a = 12, b = 20Output: 4Explanatio
    9 min read
    Stein's Algorithm for finding GCD
    Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction.Examples: Input: a = 17, b = 34 Output : 17Input: a = 50, b = 49Output: 1Algorith
    14 min read
    Program to find LCM of two numbers
    Given two positive integers a and b. Find the Least Common Multiple (LCM) of a and b.LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 10, b = 5Output : 10Explanation : 10 is the smallest number divisible by both 10 and 5Input : a = 5, b = 11Output : 55Expla
    5 min read
    GCD, LCM and Distributive Property
    Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) where, GCD = Greatest Common Divisor, LCM = Least Common MultipleExamples: Input: x = 15, y = 20, z = 100Output: 60Explanation: The GCD of 15 and 20 is 5, and the LCM of 15 and 20 is 60, which is then multiplie
    4 min read
    Euler's Totient function for all numbers smaller than or equal to n
    Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
    13 min read
    Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
    Given a number n, we need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2Output : 3The pairs are (1, 1) (2, 2) and (2, 1) Input : n = 3Output : 5(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1)[Naive Approach] Counting GCD Pairs by Divisor Propertygcd(a, b) =
    6 min read

    Problems on GCD

    Series with largest GCD and sum equals to n
    Given integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.Examples : Input
    7 min read
    Program to find GCD of floating point numbers
    The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9Output : 0.3Explanation: The GCD of 0.3 and 0.9 is 0.3 because both numbers share 0.3 as the largest common divisor.Input : 0.48
    4 min read
    Largest Subset with GCD 1
    Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
    6 min read
    Summation of GCD of all the pairs up to n
    Given a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n. Examples: Input : n = 4Output : 7Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7Input : n = 12Output
    10 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
    GCD of digits of a given number
    Given a number n, find GCD of its digits. Examples : Input : 345 Output : 1 GCD of 3, 4 and 5 is 1. Input : 2448 Output : 2 GCD of 2, 4, 4 and 8 is 2 We traverse the digits of number one by one using below loop digit = n mod 10; n = n / 10; While traversing digits, we keep track of current GCD and k
    4 min read
    Maximize GCD of all possible pairs from 1 to N
    Given an integer N (> 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N]. Example: Input: N = 5 Output: 2 Explanation : GCD(1, 2) : 1 GCD(1, 3) : 1 GCD(1, 4) : 1 GCD(1, 5) : 1 GCD(2, 3) : 1 GCD(2, 4) : 2 GCD(2, 5) : 1 GCD(3, 4) : 1 GCD(3, 5) : 1 G
    3 min read
    GCD of two numbers formed by n repeating x and y times
    Given three positive integer n, x, y. The task is to print Greatest Common Divisor of numbers formed by n repeating x times and number formed by n repeating y times. 0 <= n, x, y <= 1000000000.Examples : Input : n = 123, x = 2, y = 3. Output : 123 Number formed are 123123 and 123123123. Greate
    6 min read
    Program to find Greatest Common Divisor (GCD) of N strings
    Given an array of string arr[], the task is the Greatest Common Divisor of the given array of string. In strings 'A' and 'B', we say "B divides A" if and only if A = concatenation of B more than 1 times.Find the largest string which divides both A and B. Examples: Input: arr[] = { "GFGGFG", "GFGGFG"
    13 min read
    Find the GCD that lies in given range
    Given two positive integer a and b and a range [low, high]. The task is to find the greatest common divisor of a and b which lie in the given range. If no divisor exist in the range, print -1.Examples: Input : a = 9, b = 27, low = 1, high = 5 Output : 3 3 is the highest number that lies in range [1,
    7 min read
    Find the maximum GCD of the siblings of a Binary Tree
    Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it. Example:   Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}} Output: 6 Explanation:   For the above tree, the maxi
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences