Open In App
Related Articles

Largest divisible pairs subset

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an array of n distinct elements, find length of the largest subset such that every pair in the subset is such that the larger element of the pair is divisible by smaller element. 

Examples: 

Input : arr[] = {10, 5, 3, 15, 20} 
Output : 3
Explanation: The largest subset is 10, 5, 20.
10 is divisible by 5, and 20 is divisible by 10.
Input : arr[] = {18, 1, 3, 6, 13, 17}
Output : 4
Explanation: The largest subset is 18, 1, 3, 6,
In the subsequence, 3 is divisible by 1,
6 by 3 and 18 by 6.

Brute Force Approach: The brute force approach generates all possible subsets of the input array using bit manipulation and checks if each subset contains only pairs of elements that are divisible. It keeps track of the largest subset that satisfies this condition and returns it as the result. 

  • Initialize maxSubset = 1
  • For each subset S of the input array a:
    •  Initialize subsetSize = 0 and validSubset = true
    • For each pair of elements (a[i], a[j]) in S:
      • If a[i] % a[j] != 0 and a[j] % a[i] != 0, set validSubset = false and break out of the loop.
      •  Otherwise, continue to the next pair. 
    • If validSubset is still true, increment subsetSize by 1
    • If subsetSize is greater than maxSubset, set maxSubset = subsetSize
  • Return maxSubset as the result

C++

#include <bits/stdc++.h>
using namespace std;
 
int largestSubset(int a[], int n)
{
    int maxSubset
        = 1; // variable to store the maximum subset size
             // found so far, initialized to 1
    for (int i = 0; i < (1 << n);
         i++) { // loop through all possible subsets of the
                // input array
        int subsetSize
            = 0; // variable to store the size of the
                 // current subset being considered
        bool validSubset
            = true; // variable to keep track of whether the
                    // current subset is valid or not
        for (int j = 0; j < n;
             j++) { // loop through all elements in the
                    // input array
            if (i & (1 << j)) { // check if the j-th element
                                // is present in the current
                                // subset being considered
                for (int k = j + 1; k < n;
                     k++) { // loop through all elements
                            // after the j-th element
                    if (i
                        & (1
                           << k)) { // check if the k-th
                                    // element is present in
                                    // the current subset
                                    // being considered
                        if (a[j] % a[k] != 0
                            && a[k] % a[j]
                                   != 0) { // check if the
                                           // pair (a[j],
                                           // a[k]) is not
                                           // divisible
                            validSubset
                                = false; // if the pair is
                                         // not divisible,
                                         // mark the current
                                         // subset as
                                         // invalid
                            break; // break out of the inner
                                   // loop since we don't
                                   // need to check any more
                                   // pairs
                        }
                    }
                }
                if (validSubset) { // if the current subset
                                   // is still valid after
                                   // checking all pairs,
                                   // increment the subset
                                   // size
                    subsetSize++;
                }
                else { // if the current subset is not
                       // valid, break out of the outer loop
                       // since we don't need to consider
                       // this subset anymore
                    break;
                }
            }
        }
        maxSubset
            = max(maxSubset,
                  subsetSize); // update the maximum subset
                               // size found so far
    }
    return maxSubset; // return the maximum subset size
                      // found
}
 
int main()
{
    int a[] = {10, 5, 3, 15, 20 }; // sample input array
    int n = sizeof(a)
            / sizeof(a[0]); // size of the input array
    cout << largestSubset(a, n)
         << endl; // call the function and print the result
    return 0;
}

                    

Java

import java.util.*;
 
class Main {
    public static int largestSubset(int[] a, int n) {
        int maxSubset = 1; // variable to store the maximum subset size found so far, initialized to 1
        for (int i = 0; i < (1 << n); i++) { // loop through all possible subsets of the input array
            int subsetSize = 0; // variable to store the size of the current subset being considered
            boolean validSubset = true; // variable to keep track of whether the current subset is valid or not
            for (int j = 0; j < n; j++) { // loop through all elements in the input array
                if ((i & (1 << j)) != 0) { // check if the j-th element is present in the current subset being considered
                    for (int k = j + 1; k < n; k++) { // loop through all elements after the j-th element
                        if ((i & (1 << k)) != 0) { // check if the k-th element is present in the current subset being considered
                            if (a[j] % a[k] != 0 && a[k] % a[j] != 0) { // check if the pair (a[j], a[k]) is not divisible
                                validSubset = false; // if the pair is not divisible, mark the current subset as invalid
                                break; // break out of the inner loop since we don't need to check any more pairs
                            }
                        }
                    }
                    if (validSubset) { // if the current subset is still valid after checking all pairs, increment the subset size
                        subsetSize++;
                    } else { // if the current subset is not valid, break out of the outer loop since we don't need to consider this subset anymore
                        break;
                    }
                }
            }
            maxSubset = Math.max(maxSubset, subsetSize); // update the maximum subset size found so far
        }
        return maxSubset; // return the maximum subset size found
    }
 
    public static void main(String[] args) {
        int[] a = {10, 5, 3, 15, 20}; // sample input array
        int n = a.length; // size of the input array
        System.out.println(largestSubset(a, n)); // call the function and print the result
    }
}

                    

Python3

# Implementation of largestSubset function in Python
 
 
def largestSubset(a, n):
    maxSubset = 1  # variable to store the maximum subset size
    # found so far, initialized to 1
    for i in range(1 << n):  # loop through all possible subsets of the
                            # input array
        subsetSize = 0  # variable to store the size of the
        # current subset being considered
        validSubset = True  # variable to keep track of whether the
        # current subset is valid or not
        for j in range(n):  # loop through all elements in the
                           # input array
            if i & (1 << j):  # check if the j-th element
                             # is present in the current
                             # subset being considered
                for k in range(j + 1, n):  # loop through all elements
                                         # after the j-th element
                    if i & (1 << k):  # check if the k-th
                                     # element is present in
                                     # the current subset
                                     # being considered
                        if a[j] % a[k] != 0 and a[k] % a[j] != 0:
                            # check if the pair (a[j], a[k]) is not
                            # divisible
                            validSubset = False  # if the pair is
                            # not divisible,
                            # mark the current
                            # subset as
                            # invalid
                            break  # break out of the inner
                            # loop since we don't
                            # need to check any more
                            # pairs
                if validSubset:  # if the current subset
                                 # is still valid after
                                 # checking all pairs,
                                 # increment the subset
                                 # size
                    subsetSize += 1
                else# if the current subset is not
                      # valid, break out of the outer loop
                      # since we don't need to consider
                      # this subset anymore
                    break
        maxSubset = max(maxSubset, subsetSize)  # update the maximum subset
        # size found so far
    return maxSubset  # return the maximum subset size
    # found
 
 
# Sample input array
a = [10, 5, 3, 15, 20]
n = len(a)  # size of the input array
print(largestSubset(a, n))  # call the function and print the result

                    

C#

using System;
 
class GFG
{
    static int LargestSubset(int[] a, int n)
    {
        int maxSubset = 1; // variable to store the maximum subset size
                           // found so far, initialized to 1
        for (int i = 0; i < (1 << n); i++)
        {
            // loop through all possible subsets of the input array
            int subsetSize = 0; // variable to store the size of the
                                // current subset being considered
            bool validSubset = true; // variable to keep track of whether the
                                     // current subset is valid or not
            for (int j = 0; j < n; j++)
            {
                // loop through all elements in the input array
                if ((i & (1 << j)) != 0)
                {
                    // check if the j-th element is present in the current
                    // subset being considered
                    for (int k = j + 1; k < n; k++)
                    {
                        // loop through all elements after the j-th element
                        if ((i & (1 << k)) != 0)
                        {
                            // check if the k-th element is present in
                            // the current subset being considered
                            if (a[j] % a[k] != 0 && a[k] % a[j] != 0)
                            {
                                // check if the pair (a[j], a[k]) is not divisible
                                validSubset = false; // if the pair is not divisible,
                                                     // mark the current subset as invalid
                                break; // break out of the inner loop since we don't
                                       // need to check any more pairs
                            }
                        }
                    }
                    if (validSubset)
                    {
                        // if the current subset is still valid after
                        // checking all pairs, increment the subset size
                        subsetSize++;
                    }
                    else
                    {
                        // if the current subset is not valid, break out of the outer loop
                        // since we don't need to consider this subset anymore
                        break;
                    }
                }
            }
            maxSubset = Math.Max(maxSubset, subsetSize); // update the maximum subset
                                                        // size found so far
        }
        return maxSubset; // return the maximum subset size found
    }
 
    static void Main()
    {
        int[] a = { 10, 5, 3, 15, 20 }; // sample input array
        int n = a.Length; // size of the input array
        Console.WriteLine(LargestSubset(a, n)); // call the function and print the result
    }
}

                    

Javascript

function largestSubset(a) {
    let maxSubset = 1; // variable to store the maximum subset size found so far, initialized to 1
 
    for (let i = 0; i < (1 << a.length); i++) { // loop through all possible subsets of the input array
        let subsetSize = 0; // variable to store the size of the current subset being considered
        let validSubset = true; // variable to keep track of whether the current subset is valid or not
 
        for (let j = 0; j < a.length; j++) { // loop through all elements in the input array
            if (i & (1 << j)) { // check if the j-th element is present in the current subset being considered
                for (let k = j + 1; k < a.length; k++) { // loop through all elements after the j-th element
                    if (i & (1 << k)) { // check if the k-th element is present in the current subset being considered
                        if (a[j] % a[k] !== 0 && a[k] % a[j] !== 0) { // check if the pair (a[j], a[k]) is not divisible
                            validSubset = false; // if the pair is not divisible, mark the current subset as invalid
                            break; // break out of the inner loop since we don't need to check any more pairs
                        }
                    }
                }
                if (validSubset) { // if the current subset is still valid after checking all pairs, increment the subset size
                    subsetSize++;
                } else { // if the current subset is not valid, break out of the outer loop since we don't need to consider this subset anymore
                    break;
                }
            }
        }
        maxSubset = Math.max(maxSubset, subsetSize); // update the maximum subset size found so far
    }
 
    return maxSubset; // return the maximum subset size found
}
 
const a = [10, 5, 3, 15, 20]; // sample input array
console.log(largestSubset(a)); // call the function and print the result

                    

Output
3






Time Complexity: O(2n*n2)
Space Complexity:  O(1)

Dynamic programming Approach: This can be solved using Dynamic Programming. We traverse the sorted array from the end. For every element a[i], we compute dp[i] where dp[i] indicates size of largest divisible subset where a[i] is the smallest element. We can compute dp[i] in array using values from dp[i+1] to dp[n-1]. Finally, we return the maximum value from dp[].

Below is the implementation of the above approach:  

C++

// CPP program to find the largest subset which
// where each pair is divisible.
#include <bits/stdc++.h>
using namespace std;
 
// function to find the longest Subsequence
int largestSubset(int a[], int n)
{
    // dp[i] is going to store size of largest
    // divisible subset beginning with a[i].
    int dp[n];
 
    // Since last element is largest, d[n-1] is 1
    dp[n - 1] = 1;
 
    // Fill values for smaller elements.
    for (int i = n - 2; i >= 0; i--) {
 
        // Find all multiples of a[i] and consider
        // the multiple that has largest subset
        // beginning with it.
        int mxm = 0;
        for (int j = i + 1; j < n; j++)
            if (a[j] % a[i] == 0 || a[i] % a[j] == 0)
                mxm = max(mxm, dp[j]);
 
        dp[i] = 1 + mxm;
    }
 
    // Return maximum value from dp[]
    return *max_element(dp, dp + n);
}
 
// driver code to check the above function
int main()
{
    int a[] = { 1, 3, 6, 13, 17, 18 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << largestSubset(a, n) << endl;
    return 0;
}

                    

Java

import java.util.Arrays;
 
// Java program to find the largest
// subset which was each pair
// is divisible.
class GFG {
 
    // function to find the longest Subsequence
    static int largestSubset(int[] a, int n)
    {
        // dp[i] is going to store size of largest
        // divisible subset beginning with a[i].
        int[] dp = new int[n];
 
        // Since last element is largest, d[n-1] is 1
        dp[n - 1] = 1;
 
        // Fill values for smaller elements.
        for (int i = n - 2; i >= 0; i--) {
 
            // Find all multiples of a[i] and consider
            // the multiple that has largest subset
            // beginning with it.
            int mxm = 0;
            for (int j = i + 1; j < n; j++) {
                if (a[j] % a[i] == 0 || a[i] % a[j] == 0) {
                    mxm = Math.max(mxm, dp[j]);
                }
            }
 
            dp[i] = 1 + mxm;
        }
 
        // Return maximum value from dp[]
        return Arrays.stream(dp).max().getAsInt();
    }
 
    // driver code to check the above function
    public static void main(String[] args)
    {
        int[] a = { 1, 3, 6, 13, 17, 18 };
        int n = a.length;
        System.out.println(largestSubset(a, n));
    }
}
 
/* This JAVA code is contributed by Rajput-Ji*/

                    

Python3

# Python program to find the largest
# subset where each pair is divisible.
 
# function to find the longest Subsequence
def largestSubset(a, n):
     
    # dp[i] is going to store size
    # of largest divisible subset
    # beginning with a[i].
    dp = [0 for i in range(n)]
     
    # Since last element is largest,
    # d[n-1] is 1
    dp[n - 1] = 1;
 
    # Fill values for smaller elements
    for i in range(n - 2, -1, -1):
         
        # Find all multiples of a[i]
        # and consider the multiple
        # that has largest subset    
        # beginning with it.
        mxm = 0;
        for j in range(i + 1, n):
            if a[j] % a[i] == 0 or a[i] % a[j] == 0:
                mxm = max(mxm, dp[j])
        dp[i] = 1 + mxm
         
    # Return maximum value from dp[]
    return max(dp)
 
# Driver Code
a = [ 1, 3, 6, 13, 17, 18 ]
n = len(a)
print(largestSubset(a, n))
 
# This code is contributed by
# sahil shelangia

                    

C#

// C# program to find the largest
// subset which where each pair
// is divisible.
using System;
using System.Linq;
 
public class GFG {
 
    // function to find the longest Subsequence
    static int largestSubset(int[] a, int n)
    {
        // dp[i] is going to store size of largest
        // divisible subset beginning with a[i].
        int[] dp = new int[n];
 
        // Since last element is largest, d[n-1] is 1
        dp[n - 1] = 1;
 
        // Fill values for smaller elements.
        for (int i = n - 2; i >= 0; i--) {
 
            // Find all multiples of a[i] and consider
            // the multiple that has largest subset
            // beginning with it.
            int mxm = 0;
            for (int j = i + 1; j < n; j++)
                if (a[j] % a[i] == 0 | a[i] % a[j] == 0)
                    mxm = Math.Max(mxm, dp[j]);
 
            dp[i] = 1 + mxm;
        }
 
        // Return maximum value from dp[]
        return dp.Max();
    }
 
    // driver code to check the above function
    static public void Main()
    {
        int[] a = { 1, 3, 6, 13, 17, 18 };
        int n = a.Length;
        Console.WriteLine(largestSubset(a, n));
    }
}
 
// This code is contributed by vt_m.

                    

Javascript

<script>
 
// Javascript program to find the largest
// subset which was each pair
// is divisible.
 
// Function to find the longest Subsequence
function largestSubset(a, n)
{
     
    // dp[i] is going to store size of largest
    // divisible subset beginning with a[i].
    let dp = [];
 
    // Since last element is largest, d[n-1] is 1
    dp[n - 1] = 1;
 
    // Fill values for smaller elements.
    for(let i = n - 2; i >= 0; i--)
    {
         
        // Find all multiples of a[i] and consider
        // the multiple that has largest subset
        // beginning with it.
        let mxm = 0;
        for(let j = i + 1; j < n; j++)
        {
            if (a[j] % a[i] == 0 ||
                a[i] % a[j] == 0)
            {
                mxm = Math.max(mxm, dp[j]);
            }
        }
        dp[i] = 1 + mxm;
    }
 
    // Return maximum value from dp[]
    return Math.max(...dp);
}
 
// Driver code
let a = [ 1, 3, 6, 13, 17, 18 ];
let n = a.length;
 
document.write(largestSubset(a, n));
 
// This code is contributed by sanjoy_62
 
</script>

                    

PHP

<?php
// PHP program to find the
// largest subset which
// where each pair is
// divisible.
 
// function to find the
// longest Subsequence
function largestSubset($a, $n)
{
    // dp[i] is going to
    // store size of largest
    // divisible subset
    // beginning with a[i].
    $dp = array();
 
    // Since last element is
    // largest, d[n-1] is 1
    $dp[$n - 1] = 1;
 
    // Fill values for
    // smaller elements.
    for ($i = $n - 2; $i >= 0; $i--)
    {
 
        // Find all multiples of
        // a[i] and consider
        // the multiple that
        // has largest subset
        // beginning with it.
        $mxm = 0;
        for ($j = $i + 1; $j < $n; $j++)
            if ($a[$j] % $a[$i] == 0 or $a[$i] % $a[$j] == 0)
                $mxm = max($mxm, $dp[$j]);
 
        $dp[$i] = 1 + $mxm;
    }
 
    // Return maximum value
    // from dp[]
    return max($dp);
}
 
    // Driver Code
    $a = array(1, 3, 6, 13, 17, 18);
    $n = count($a);
    echo largestSubset($a, $n);
     
// This code is contributed by anuj_67.
?>

                    

Output
4






Time Complexity: O(n2)
Space Complexity: O(n)

Largest divisible pairs subset in c:

Approach

1. Create an array dp of size n to store the size of the largest divisible subset ending with each element of the array arr.

2. Initialize all elements of the dp array to 1, as every element is a divisible subset of itself.

3. For every element arr[i] in the array, check all previous elements arr[j] (where j < i) to see if arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i].

4. If arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i], then we can extend the divisible subset ending with arr[j] by including the arr[i] element as well. We will choose the arr[j] element which gives the largest divisible subset ending with arr[j].

5. Update the dp array with the size of the largest divisible subset ending with arr[i].

6. Keep track of the maximum element in the dp array, which gives the largest divisible subset among all elements.

7. Return the maximum element in the dp array.

8. In the main() function, create an array arr of integers and call the largest_divisible_pairs_subset() function with the array and its size.

9. Print the result returned by the largest_divisible_pairs_subset() function, which gives the size of the largest divisible subset.

C++

#include <bits/stdc++.h>
using namespace std;
 
int largest_divisible_pairs_subset(int arr[], int n) {
    vector<int> dp(n, 1);
    int max_dp = 1;
 
    // Compute dp array
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0) {
                dp[i] = max(dp[j] + 1, dp[i]);
            }
        }
        max_dp = max(dp[i], max_dp);
    }
 
    return max_dp;
}
 
int main() {
    int arr[] = {3, 5, 10, 20, 21, 33};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << largest_divisible_pairs_subset(arr, n);
    return 0;
}

                    

C

#include <stdio.h>
#include <stdlib.h>
 
int largest_divisible_pairs_subset(int arr[], int n) {
    int dp[n];
    int i, j, max_dp = 1;
     
    // Initialize dp array
    for (i = 0; i < n; i++) {
        dp[i] = 1;
    }
     
    // Compute dp array
    for (i = 1; i < n; i++) {
        for (j = 0; j < i; j++) {
            if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0) {
                dp[i] = dp[j] + 1 > dp[i] ? dp[j] + 1 : dp[i];
            }
        }
        max_dp = dp[i] > max_dp ? dp[i] : max_dp;
    }
     
    return max_dp;
}
 
int main() {
    int arr[] = {3, 5, 10, 20, 21, 33};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("%d", largest_divisible_pairs_subset(arr, n));
    return 0;
}

                    

Java

// Java program for the above approach
import java.util.*;
 
public class Main {
 
    // Function to find the largest divisible
    // subset in a given array
    public static int largestDivisiblePairsSubset(int arr[],
                                                  int n)
    {
        // Stores the recurring state
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        int maxDp = 1;
 
        // Compute dp array
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[i] % arr[j] == 0
                    || arr[j] % arr[i] == 0) {
                    dp[i] = Math.max(dp[j] + 1, dp[i]);
                }
            }
            maxDp = Math.max(dp[i], maxDp);
        }
 
        // Return the maximum value
        return maxDp;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 3, 5, 10, 20, 21, 33 };
        int n = arr.length;
 
        System.out.println(
            largestDivisiblePairsSubset(arr, n));
    }
}

                    

Python3

import sys
 
def largest_divisible_pairs_subset(arr, n):
    dp = [1] * n
    max_dp = 1
 
    # Compute dp array
    for i in range(1, n):
        for j in range(i):
            if arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0:
                dp[i] = max(dp[j] + 1, dp[i])
        max_dp = max(dp[i], max_dp)
 
    return max_dp
 
if __name__ == '__main__':
    arr = [3, 5, 10, 20, 21, 33]
    n = len(arr)
    print(largest_divisible_pairs_subset(arr, n))
 
# This code is contributed by shivhack9999

                    

C#

using System;
 
class GFG {
    static int largest_divisible_pairs_subset(int[] arr,
                                              int n)
    {
        // Initialize dp array
        int[] dp = new int[n];
        for (int i = 0; i < n; i++)
            dp[i] = 1;
        int max_dp = 1;
 
        // Compute dp array
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[i] % arr[j] == 0
                    || arr[j] % arr[i] == 0) {
                    dp[i] = Math.Max(dp[j] + 1, dp[i]);
                }
            }
            max_dp = Math.Max(dp[i], max_dp);
        }
 
        return max_dp;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 3, 5, 10, 20, 21, 33 };
        int n = arr.Length;
        Console.WriteLine(
            largest_divisible_pairs_subset(arr, n));
    }
}

                    

Javascript

function largest_divisible_pairs_subset(arr, n) {
    const dp = new Array(n).fill(1);
    let max_dp = 1;
 
    // Compute dp array
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
            if (arr[i] % arr[j] === 0 || arr[j] % arr[i] === 0) {
                dp[i] = Math.max(dp[j] + 1, dp[i]);
            }
        }
        max_dp = Math.max(dp[i], max_dp);
    }
 
    return max_dp;
}
 
const arr = [3, 5, 10, 20, 21, 33];
const n = arr.length;
console.log(largest_divisible_pairs_subset(arr, n));

                    

Output
3






Time Complexity:
The time complexity of the above algorithm is O(n^2), as we need to check all previous elements for each element.

Auxiliary Space:
The space complexity of the above algorithm is O(n), as we are only using an array of size n to store the largest divisible subset ending with each element.



Last Updated : 31 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads