Count sub-arrays whose product is divisible by k

Given an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.

Examples:

Input: arr[] = {6, 2, 8}, K = 4
Output: 4
Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.



Input: arr[] = {9, 1, 14}, K = 6
Output: 1

Naive approach: Run nested loops and check for every sub-array whether product % k == 0. Update count = count + 1 when the condition is true for the sub-array. Time complexity of this approach is O(n3).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
  
// Function to count sub-arrays whose
// product is divisible by K
int countSubarrays(const int* arr, int n, int K)
{
    int count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
  
            // Calculate the product of the
            // current sub-array
            ll product = 1;
            for (int x = i; x <= j; x++)
                product *= arr[x];
  
            // If product of the current sub-array
            // is divisible by K
            if (product % K == 0)
                count++;
        }
    }
    return count;
}
  
// Driver code
int main()
{
    int arr[] = { 6, 2, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 4;
    cout << countSubarrays(arr, n, K);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG 
{
  
// Function to count sub-arrays whose
// product is divisible by K
static int countSubarrays(int []arr, int n, int K)
{
    int count = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
  
            // Calculate the product of the
            // current sub-array
            long product = 1;
            for (int x = i; x <= j; x++)
                product *= arr[x];
  
            // If product of the current sub-array
            // is divisible by K
            if (product % K == 0)
                count++;
        }
    }
    return count;
}
  
// Driver code
public static void main(String[] args) 
{
    int arr[] = { 6, 2, 8 };
    int n = arr.length;
    int K = 4;
    System.out.println(countSubarrays(arr, n, K));
}
}
  
// This code contributed by Rajput-Ji

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
  
# Function to count sub-arrays whose
# product is divisible by K
def countSubarrays(arr, n, K):
  
    count = 0
    for i in range( n):
        for j in range(i, n):
  
            # Calculate the product of 
            # the current sub-array
            product = 1
            for x in range(i, j + 1):
                product *= arr[x]
  
            # If product of the current 
            # sub-array is divisible by K
            if (product % K == 0):
                count += 1
    return count
  
# Driver code
if __name__ == "__main__":
  
    arr = [ 6, 2, 8 ]
    n = len(arr)
    K = 4
    print(countSubarrays(arr, n, K))
  
# This code is contributed by ita_c 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
  
class GFG 
{
    // Function to count sub-arrays whose 
    // product is divisible by K 
    static int countSubarrays(int []arr, int n, int K) 
    
        int count = 0; 
        for (int i = 0; i < n; i++) 
        
            for (int j = i; j < n; j++) 
            
      
                // Calculate the product of the 
                // current sub-array 
                long product = 1; 
                for (int x = i; x <= j; x++) 
                    product *= arr[x]; 
      
                // If product of the current sub-array 
                // is divisible by K 
                if (product % K == 0) 
                    count++; 
            
        
        return count; 
    
      
    // Driver code 
    public static void Main() 
    
        int []arr = { 6, 2, 8 }; 
        int n = arr.Length; 
        int K = 4; 
          
        Console.WriteLine(countSubarrays(arr, n, K)); 
    
  
// This code contributed by Rajput-Ji 

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the approach
  
// Function to count sub-arrays whose
// product is divisible by K
function countSubarrays($arr, $n, $K)
{
    $count = 0;
    for ($i = 0; $i < $n; $i++) 
    {
        for ($j = $i; $j < $n; $j++)
        {
  
            // Calculate the product of the
            // current sub-array
            $product = 1;
            for ($x = $i; $x <= $j; $x++)
                $product *= $arr[$x];
  
            // If product of the current 
            // sub-array is divisible by K
            if ($product % $K == 0)
                $count++;
        }
    }
    return $count;
}
  
// Driver code
$arr = array( 6, 2, 8 );
$n = count($arr);
$K = 4;
echo countSubarrays($arr, $n, $K);
  
// This code is contributed by mits
?>

chevron_right


Output:

4

A better approach is to either use the two-pointer technique or use segment trees to find the product of a sub-array in quick time.

Segment trees: The complexity of the naive solution is cubic. This is because every sub-array is traversed to find the product. Instead of traversing every sub-array, products can be stored in a segment tree and the tree can be queried to obtain the product % k value in O(log n) time. Thus, time complexity of this approach would then be O(n2 log n).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MAX 100002
  
// Segment tree implemented as an array
ll tree[4 * MAX];
  
// Function to build the segment tree
void build(int node, int start, int end, const int* arr, int k)
{
    if (start == end) {
        tree[node] = (1LL * arr[start]) % k;
        return;
    }
    int mid = (start + end) >> 1;
    build(2 * node, start, mid, arr, k);
    build(2 * node + 1, mid + 1, end, arr, k);
    tree[node] = (tree[2 * node] * tree[2 * node + 1]) % k;
}
  
// Function to query product of
// sub-array[l..r] in O(log n) time
ll query(int node, int start, int end, int l, int r, int k)
{
    if (start > end || start > r || end < l) {
        return 1;
    }
    if (start >= l && end <= r) {
        return tree[node] % k;
    }
    int mid = (start + end) >> 1;
    ll q1 = query(2 * node, start, mid, l, r, k);
    ll q2 = query(2 * node + 1, mid + 1, end, l, r, k);
    return (q1 * q2) % k;
}
  
// Function to count sub-arrays whose
// product is divisible by K
ll countSubarrays(const int* arr, int n, int k)
{
    ll count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
  
            // Query segment tree to find product % k
            // of the sub-array[i..j]
            ll product_mod_k = query(1, 0, n - 1, i, j, k);
            if (product_mod_k == 0) {
                count++;
            }
        }
    }
    return count;
}
  
// Driver code
int main()
{
    int arr[] = { 6, 2, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
  
    // Build the segment tree
    build(1, 0, n - 1, arr, k);
  
    cout << countSubarrays(arr, n, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

    // Java implementation for above approach
class GFG
{
      
static int MAX = 100002;
  
// Segment tree implemented as an array
static long tree[] = new long[4 * MAX];
  
// Function to build the segment tree
static void build(int node, int start, int end, 
                            int []arr, int k)
{
    if (start == end)
    {
        tree[node] = (1L * arr[start]) % k;
        return;
    }
    int mid = (start + end) >> 1;
    build(2 * node, start, mid, arr, k);
    build(2 * node + 1, mid + 1, end, arr, k);
    tree[node] = (tree[2 * node] * tree[2 * node + 1]) % k;
}
  
// Function to query product of
// sub-array[l..r] in O(log n) time
static long query(int node, int start, int end, 
                            int l, int r, int k)
{
    if (start > end || start > r || end < l) 
    {
        return 1;
    }
    if (start >= l && end <= r) 
    {
        return tree[node] % k;
    }
    int mid = (start + end) >> 1;
    long q1 = query(2 * node, start, mid, l, r, k);
    long q2 = query(2 * node + 1, mid + 1, end, l, r, k);
    return (q1 * q2) % k;
}
  
// Function to count sub-arrays whose
// product is divisible by K
static long countSubarrays(int []arr, int n, int k)
{
    long count = 0;
    for (int i = 0; i < n; i++) 
    {
        for (int j = i; j < n; j++) 
        {
  
            // Query segment tree to find product % k
            // of the sub-array[i..j]
            long product_mod_k = query(1, 0, n - 1, i, j, k);
            if (product_mod_k == 0
            {
                count++;
            }
        }
    }
    return count;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 6, 2, 8 };
    int n = arr.length;
    int k = 4;
  
    // Build the segment tree
    build(1, 0, n - 1, arr, k);
  
    System.out.println(countSubarrays(arr, n, k));
}
}
  
// This code has been contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation for above approach
using System;
  
class GFG
{
      
static int MAX = 100002;
  
// Segment tree implemented as an array
static long []tree = new long[4 * MAX];
  
// Function to build the segment tree
static void build(int node, int start, int end, 
                            int []arr, int k)
{
    if (start == end)
    {
        tree[node] = (1L * arr[start]) % k;
        return;
    }
    int mid = (start + end) >> 1;
    build(2 * node, start, mid, arr, k);
    build(2 * node + 1, mid + 1, end, arr, k);
    tree[node] = (tree[2 * node] * tree[2 * node + 1]) % k;
}
  
// Function to query product of
// sub-array[l..r] in O(log n) time
static long query(int node, int start, int end, 
                            int l, int r, int k)
{
    if (start > end || start > r || end < l) 
    {
        return 1;
    }
    if (start >= l && end <= r) 
    {
        return tree[node] % k;
    }
    int mid = (start + end) >> 1;
    long q1 = query(2 * node, start, mid, l, r, k);
    long q2 = query(2 * node + 1, mid + 1, end, l, r, k);
    return (q1 * q2) % k;
}
  
// Function to count sub-arrays whose
// product is divisible by K
static long countSubarrays(int []arr, int n, int k)
{
    long count = 0;
    for (int i = 0; i < n; i++) 
    {
        for (int j = i; j < n; j++) 
        {
  
            // Query segment tree to find product % k
            // of the sub-array[i..j]
            long product_mod_k = query(1, 0, n - 1, i, j, k);
            if (product_mod_k == 0) 
            {
                count++;
            }
        }
    }
    return count;
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 6, 2, 8 };
    int n = arr.Length;
    int k = 4;
  
    // Build the segment tree
    build(1, 0, n - 1, arr, k);
  
    Console.WriteLine(countSubarrays(arr, n, k));
}
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


Output:

4

Further optimizing the solution: It is understandable that if the product of a sub-array [i..j] is divisible by k, then the product of all subarrays [i..t] such that j < t < n will also be divisible by k. Hence binary search can be applied to count sub-arrays starting at a particular index i and whose product is divisible by k.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
typedef long long ll;
  
// Segment tree implemented as an array
ll tree[MAX << 2];
  
// Function to build segment tree
void build(int node, int start, int end, const int* arr, int k)
{
    if (start == end) {
        tree[node] = arr[start] % k;
        return;
    }
    int mid = (start + end) >> 1;
    build(2 * node, start, mid, arr, k);
    build(2 * node + 1, mid + 1, end, arr, k);
    tree[node] = (tree[2 * node] * tree[2 * node + 1]) % k;
}
  
// Function to query product % k
// of sub-array[l..r]
ll query(int node, int start, int end, int l, int r, int k)
{
    if (start > end || start > r || end < l)
        return 1;
    if (start >= l && end <= r)
        return tree[node] % k;
    int mid = (start + end) >> 1;
    ll q1 = query(2 * node, start, mid, l, r, k);
    ll q2 = query(2 * node + 1, mid + 1, end, l, r, k);
    return (q1 * q2) % k;
}
  
// Function to return the count of sub-arrays
// whose product is divisible by K
ll countSubarrays(int* arr, int n, int k)
{
  
    ll ans = 0;
  
    for (int i = 0; i < n; i++) {
  
        int low = i, high = n - 1;
  
        // Binary search
        // Check if sub-array[i..mid] satisfies the constraint
        // Adjust low and high accordingly
        while (low <= high) {
            int mid = (low + high) >> 1;
            if (query(1, 0, n - 1, i, mid, k) == 0)
                high = mid - 1;
            else
                low = mid + 1;
        }
        ans += n - low;
    }
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 6, 2, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
  
    // Build the segment tree
    build(1, 0, n - 1, arr, k);
  
    cout << countSubarrays(arr, n, k);
  
    return 0;
}

chevron_right


Output:

4

Two pointers technique: Analogous to the binary-search discussion, it is clear that if sub-array[i..j] has product divisible by k, then all sub-arrays [i..t] such that j < t < n will also have products divisible by k.

Hence, two-pointer technique can also be applied here corresponding to the above fact. Two pointers l, r are taken with l pointing to the start of the current sub-array and r pointing to the end of the current sub-array. If the sub-array [l..r] has product divisible by k, then all sub-arrays [l..s] such that r < s < n will have product divisible by k. Therefore perform count = count + n – r. Since elements need to be added and removed from the current sub-array, simply products can’t be taken of the whole sub-array since it will be cumbersome to add and remove elements in this way.

Instead, k is prime factorized in O(sqrt(n)) time and its prime-factors are stored in an STL map. Another map is used to maintain counts of primes in the current sub-array which may be called current map in this context. Then whenever an element needs to be added in the current sub-array, then count of those primes is added to the current map which occur in prime factorization of k. Whenever an element needs to be removed from the current map, then count of primes is similarly subtracted.

Below is the implementation of the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MAX 100002
#define pb push_back
  
// Vector to store primes
vector<int> primes;
  
// k_cnt stores count of prime factors of k
// current_map stores the count of primes
// in the current sub-array
// cnts[] is an array of maps which stores
// the count of primes for element at index i
unordered_map<int, int> k_cnt, current_map, cnts[MAX];
  
// Function to store primes in
// the vector primes
void sieve()
{
  
    int prime[MAX];
    prime[0] = prime[1] = 1;
    for (int i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            for (int j = i * 2; j < MAX; j += i) {
                if (prime[j] == 0) {
                    prime[j] = i;
                }
            }
        }
    }
  
    for (int i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            prime[i] = i;
            primes.pb(i);
        }
    }
}
  
// Function to count sub-arrays whose product
// is divisible by k
ll countSubarrays(int* arr, int n, int k)
{
  
    // Special case
    if (k == 1) {
        cout << (1LL * n * (n + 1)) / 2;
        return 0;
    }
  
    vector<int> k_primes;
  
    for (auto p : primes) {
        while (k % p == 0) {
            k_primes.pb(p);
            k /= p;
        }
    }
  
    // If k is prime and is more than 10^6
    if (k > 1) {
        k_primes.pb(k);
    }
  
    for (auto num : k_primes) {
        k_cnt[num]++;
    }
  
    // Two pointers initialized
    int l = 0, r = 0;
  
    ll ans = 0;
  
    while (r < n) {
  
        // Add rth element to the current segment
        for (auto& it : k_cnt) {
  
            // p = prime factor of k
            int p = it.first;
  
            while (arr[r] % p == 0) {
                current_map[p]++;
                cnts[r][p]++;
                arr[r] /= p;
            }
        }
  
        // Check if current sub-array's product
        // is divisible by k
        int flag = 0;
        for (auto& it : k_cnt) {
            int p = it.first;
            if (current_map[p] < k_cnt[p]) {
                flag = 1;
                break;
            }
        }
  
        // If for all prime factors p of k,
        // current_map[p] >= k_cnt[p]
        // then current sub-array is divisible by k
  
        if (!flag) {
  
            // flag = 0 means that after adding rth element
            // segment's product is divisible by k
            ans += n - r;
  
            // Eliminate 'l' from the current segment
            for (auto& it : k_cnt) {
                int p = it.first;
                current_map[p] -= cnts[l][p];
            }
  
            l++;
        }
        else {
            r++;
        }
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 6, 2, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
  
    sieve();
  
    cout << countSubarrays(arr, n, k);
  
    return 0;
}

chevron_right


Output:

4


My Personal Notes arrow_drop_up

An enthusiastic Java and web developer with a little affinity for tea, cricket, English, etymology, and reading

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.