![]() |
VOOZH | about |
Given an array of N numbers, the task is to count the number of subsequences that have gcd equal to 1.
Examples:
Input: a[] = {3, 4, 8, 16}
Output: 7
The subsequences are:
{3, 4}, {3, 8}, {3, 16}, {3, 4, 8},
{3, 4, 16}, {3, 8, 16}, {3, 4, 8, 16}
Input: a[] = {1, 2, 4}
Output: 4
A simple solution is to generate all subsequences or subsets. For every subsequence, check if its GCD is 1 or not. If 1, increment the result.
When we have values in the array (say all smaller than 1000), we can optimize the above solution as we know that number of possible GCDs would be small. We modify the recursive subset generation algorithm was considering two cases for every element, we either include or exclude it. We keep track of the current GCD and if we have already counted for this GCD, we return the count. So when we are considering a subset, some GCDs would appear again and again. Therefore the problem can be solved using Dynamic Programming. Given below are the steps to solve the above problem:
Below is the implementation of the above approach:
7
Complexity Analysis:
Alternate Solution: Count the number of subsets of a set with GCD equal to a given number
Dynamic programming approach to this problem without memoization:
Basically, the approach will be making a 2d matrix in which i coordinate will be the position of elements of the given array and the j coordinate will be numbers from 0 to 100 ie. gcd can vary from 0 to 100 if array elements are not enough large. we will iterate on the given array and the 2d matrix will store information that till ith position that how many subsequences are there having gcd vary from 1 to 100. later on, we will add dp[i][1] to get all subsequences having gcd as 1.
Below is the implementation of the above approach:
7
Complexity Analysis: