Find the count of subsequences where each element is divisible by K
Last Updated :
10 Mar, 2022
Given an array arr[] and an integer K, the task is to find the total number of subsequences from the array where each element is divisible by K.
Examples:
Input: arr[] = {1, 2, 3, 6}, K = 3
Output: 3
{3}, {6} and {3, 6} are the only valid subsequences.
Input: arr[] = {5, 10, 15, 20, 25}, K = 5
Output: 31
Approach: Since each of the elements must be divisible by K, total subsequences are equal to 2cnt where cnt is the number of elements in the array that are divisible by K. Note that 1 will be subtracted from the result in order to exclude the empty subsequence. So, the final result will be 2cnt – 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubSeq( int arr[], int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] % k == 0) {
count++;
}
}
return ( pow (2, count) - 1);
}
int main()
{
int arr[] = { 1, 2, 3, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
cout << countSubSeq(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int countSubSeq( int arr[], int n, int k)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] % k == 0 )
{
count++;
}
}
return ( int ) (Math.pow( 2 , count) - 1 );
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 6 };
int n = arr.length;
int k = 3 ;
System.out.println(countSubSeq(arr, n, k));
}
}
|
Python3
def countSubSeq(arr, n, k) :
count = 0 ;
for i in range (n) :
if (arr[i] % k = = 0 ) :
count + = 1 ;
return ( 2 * * count - 1 );
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 6 ];
n = len (arr);
k = 3 ;
print (countSubSeq(arr, n, k));
|
C#
using System;
class GFG
{
static int countSubSeq( int []arr, int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
if (arr[i] % k == 0)
{
count++;
}
}
return ( int ) (Math.Pow(2, count) - 1);
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 6 };
int n = arr.Length;
int k = 3;
Console.WriteLine(countSubSeq(arr, n, k));
}
}
|
Javascript
<script>
function countSubSeq(arr, n, k)
{
let count = 0;
for (let i = 0; i < n; i++) {
if (arr[i] % k == 0) {
count++;
}
}
return (Math.pow(2, count) - 1);
}
let arr = [ 1, 2, 3, 6 ];
let n = arr.length;
let k = 3;
document.write(countSubSeq(arr, n, k));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...