Open In App

Count sub-arrays whose product is divisible by k

Improve
Improve
Like Article
Like
Save
Share
Report

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:
Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.
Input: arr[] = {9, 1, 14}, K = 6 
Output:
 

 

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++




// 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;
}


Java




// 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


Python 3




# 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


C#




// 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


PHP




<?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
?>


Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to count sub-arrays whose
    // product is divisible by K
    function countSubarrays(arr, n, K)
    {
        let count = 0;
        for (let i = 0; i < n; i++)
        {
            for (let j = i; j < n; j++)
            {
      
                // Calculate the product of the
                // current sub-array
                let product = 1;
                for (let 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
    let arr = [ 6, 2, 8 ];
    let n = arr.length;
    let K = 4;
    document.write(countSubarrays(arr, n, K));
     
    // This code is contributed by mukesh07.
</script>


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++




// 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;
}


Java




    // 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


Python3




# Python3 implementation of the approach
 
MAX = 100002
 
# Segment tree implemented as an array
tree = [0 for  i in range(4 * MAX)];
 
# Function to build the segment tree
def build(node, start, end, arr, k):
 
    if (start == end):
        tree[node] = (arr[start]) % k;
        return;
     
    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
def query(node, start, end, l, r, k):
    if (start > end or start > r or end < l):
        return 1;
    if (start >= l and end <= r):
        return tree[node] % k;
     
    mid = (start + end) >> 1;
    q1 = query(2 * node, start, mid, l, r, k);
    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
def countSubarrays(arr, n, k):
    count = 0;
    for i in range(n):
        for j in range(i, n):
 
            # Query segment tree to find product % k
            # of the sub-array[i..j]
            product_mod_k = query(1, 0, n - 1, i, j, k);
            if (product_mod_k == 0):
                count += 1
             
    return count;
 
# Driver code
if __name__=='__main__':
 
    arr = [ 6, 2, 8 ]
    n = len(arr)
    k = 4;
 
    # Build the segment tree
    build(1, 0, n - 1, arr, k);
    print(countSubarrays(arr, n, k))
 
# This code is contributed by pratham76.


C#




// 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 */


Javascript




<script>
 
// JavaScript implementation for above approach
 
let MAX = 100002;
 
// Segment tree implemented as an array
let tree = new Array(4 * MAX);
 
// Function to build the segment tree
function build(node,start,end,arr,k)
{
    if (start == end)
    {
        tree[node] = (1 * arr[start]) % k;
        return;
    }
    let 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
function query(node,start,end,l,r,k)
{
    if (start > end || start > r || end < l)
    {
        return 1;
    }
    if (start >= l && end <= r)
    {
        return tree[node] % k;
    }
    let mid = (start + end) >> 1;
    let q1 = query(2 * node, start, mid, l, r, k);
    let 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
function countSubarrays(arr,n,k)
{
    let count = 0;
    for (let i = 0; i < n; i++)
    {
        for (let j = i; j < n; j++)
        {
  
            // Query segment tree to find product % k
            // of the sub-array[i..j]
            let product_mod_k = query(1, 0, n - 1, i, j, k);
            if (product_mod_k == 0)
            {
                count++;
            }
        }
    }
    return count;
}
 
// Driver code
let arr=[ 6, 2, 8];
let n = arr.length;
let k = 4;
 
// Build the segment tree
build(1, 0, n - 1, arr, k);
 
document.write(countSubarrays(arr, n, k));
 
 
// This code is contributed by rag2127
 
</script>


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.
 

CPP




// 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;
}


Java




// Java implementation of the approach
class GFG
{
  static int MAX = 100005;
 
  // Segment tree implemented as an array
  static int tree[] = new int[MAX << 2];
 
  // Function to build segment tree
  static void build(int node, int start,
                    int end, 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]
  static int 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;
    int q1 = query(2 * node, start, mid, l, r, k);
    int 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
  static int countSubarrays(int arr[], int n, int k)
  {      
    int 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
  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 is contributed by divyesh072019


Python3




# Python3 implementation of the approach
MAX = 100005
 
# Segment tree implemented as an array
tree = [0 for i in range(MAX << 2)];
 
# Function to build segment tree
def build(node, start, end,  arr, k):
    if (start == end):
        tree[node] = arr[start] % k;
        return;   
    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]
def query(node, start, end, l, r, k):
    if (start > end or start > r or end < l):
        return 1;
    if (start >= l and end <= r):
        return tree[node] % k;
    mid = (start + end) >> 1;
    q1 = query(2 * node, start, mid, l, r, k);
    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
def countSubarrays(arr, n, k):
    ans = 0;
    for i in range(n):
        low = i
        high = n - 1;
 
        # Binary search
        # Check if sub-array[i..mid] satisfies the constraint
        # Adjust low and high accordingly
        while (low <= high):
            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
if __name__=='__main__':
 
    arr = [ 6, 2, 8 ]
    n = len(arr)
    k = 4;
 
    # Build the segment tree
    build(1, 0, n - 1, arr, k);
    print(countSubarrays(arr, n, k))
 
    # This code is contributed by rutvik_56.


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
     
    static int MAX = 100005;
 
  // Segment tree implemented as an array
  static int[] tree = new int[MAX << 2];
 
  // Function to build segment tree
  static void build(int node, int start,
                    int end, 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]
  static int 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;
    int q1 = query(2 * node, start, mid, l, r, k);
    int 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
  static int countSubarrays(int[] arr, int n, int k)
  {      
    int 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
  static void Main() {
    int[] arr = { 6, 2, 8 };
    int n = arr.Length;
    int k = 4;
 
    // Build the segment tree
    build(1, 0, n - 1, arr, k);
    Console.Write(countSubarrays(arr, n, k));
  }
}
 
// This code is contributed by divyeshrbadiya07


Javascript




<script>
// Javascript implementation of the approach
let MAX = 100005;
 
// Segment tree implemented as an array
let tree = new Array(MAX << 2);
 
// Function to build segment tree
function build(node, start, end, arr, k)
{
    if (start == end)
    {
      tree[node] = arr[start] % k;
      return;
    }
    let 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]
function query(node,start,end,l,r,k)
{
    if (start > end || start > r || end < l)
      return 1;
    if (start >= l && end <= r)
      return tree[node] % k;
    let mid = (start + end) >> 1;
    let q1 = query(2 * node, start, mid, l, r, k);
    let 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
function countSubarrays(arr,n,k)
{
    let ans = 0;     
    for (let i = 0; i < n; i++)
    {
      let low = i, high = n - 1;
  
      // Binary search
      // Check if sub-array[i..mid] satisfies the constraint
      // Adjust low and high accordingly
      while (low <= high)
      {
        let 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
let arr = [6, 2, 8];
let n = arr.length;
let k = 4;
 
// Build the segment tree
build(1, 0, n - 1, arr, k);
document.write(countSubarrays(arr, n, k));
 
// This code is contributed by avanitrachhadiya2155.
</script>


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 occurs 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.
 

CPP




// 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;
}


Java




// Java implementation of the approach
import java.util.*;
public class GFG {
 
  static int MAX = 100002;
 
  // Vector to store primes
  static ArrayList<Integer> primes
    = new ArrayList<Integer>();
 
  // 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
  static HashMap<Integer, Integer> k_cnt
    = new HashMap<Integer, Integer>();
  static HashMap<Integer, Integer> current_map
    = new HashMap<>();
  static ArrayList<HashMap<Integer, Integer> > cnts
    = new ArrayList<HashMap<Integer, Integer> >();
 
  // Function to store primes in
  // the vector primes
  static void sieve()
  {
 
    ArrayList<Integer> prime = new ArrayList<Integer>();
    for (int i = 0; i < MAX; i++)
      prime.add(0);
    prime.set(0, 1);
    prime.set(1, 1);
    for (int i = 2; i < MAX; i++) {
      if (prime.get(i) == 0) {
        for (int j = i * 2; j < MAX; j += i) {
          if (prime.get(j) == 0) {
            prime.set(j, i);
          }
        }
      }
    }
 
    for (int i = 2; i < MAX; i++) {
      if (prime.get(i) == 0) {
        prime.set(i, i);
        primes.add(i);
      }
    }
  }
 
  // Function to count sub-arrays whose product
  // is divisible by k
  static int countSubarrays(int[] arr, int n, int k)
  {
 
    // Special case
    if (k == 1) {
      System.out.println(
        (int)((1 * n * (n + 1)) / 2));
      return 0;
    }
 
    ArrayList<Integer> k_primes
      = new ArrayList<Integer>();
 
    for (Integer p : primes) {
      while (k % p == 0) {
        k_primes.add(p);
        k /= p;
      }
    }
 
    // If k is prime and is more than 10^6
    if (k > 1) {
      k_primes.add(k);
    }
 
    for (Integer num : k_primes) {
      if (!k_cnt.containsKey(num))
        k_cnt.put(num, 0);
      k_cnt.put(num, k_cnt.get(num) + 1);
    }
 
    // Two pointers initialized
    int l = 0;
    int r = 0;
 
    int ans = 0;
 
    while (r < n) {
 
      // Add rth element to the current segment
      for (Map.Entry<Integer, Integer> entry :
           k_cnt.entrySet()) {
 
        int it = entry.getKey();
        int p = entry.getValue();
        // p = prime factor of k
 
        while (arr[r] % p == 0) {
          if (!current_map.containsKey(p))
            current_map.put(p, 0);
          current_map.put(p,
                          current_map.get(p) + 1);
 
          HashMap<Integer, Integer> h1
            = cnts.get(r);
          if (!h1.containsKey(p)) {
 
            h1.put(p, 0);
            cnts.set(r, h1);
          }
          h1.put(p, h1.get(p) + 1);
          cnts.set(r, h1);
          arr[r] = (int)(arr[r] / p);
        }
      }
 
      // Check if current sub-array's product
      // is divisible by k
      int flag = 0;
      for (Map.Entry<Integer, Integer> entry :
           k_cnt.entrySet()) {
 
        int it = entry.getKey();
        int p = entry.getValue();
        if (current_map.get(p) < k_cnt.get(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 == 0) {
 
        // 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 (Map.Entry<Integer, Integer> entry :
             k_cnt.entrySet()) {
 
          int it = entry.getKey();
          int p = entry.getValue();
          p = it;
          current_map.put(
            p, current_map.get(p)
            - cnts.get(l).get(p));
        }
 
        l++;
      }
      else {
        r++;
      }
    }
 
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    for (int i = 0; i < MAX; i++)
      cnts.add(new HashMap<Integer, Integer>());
 
    int[] arr = { 6, 2, 8 };
    int n = arr.length;
    int k = 4;
    sieve();
    System.out.println(countSubarrays(arr, n, k));
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 implementation of the approach
MAX = 100002
 
# Vector to store primes
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
k_cnt = dict();
current_map = dict();
cnts = [ dict() for _ in range(MAX)];
 
# def to store primes in
# the vector primes
def sieve():
    global k_cnt, current_map, cnts
 
    prime = [0 for _ in range(MAX)]
    prime[0] = 1
    prime[1] = 1;
    for i in range(2, MAX):
        if (prime[i] == 0) :
            for j in range(i * 2, MAX, i):
                if (prime[j] == 0) :
                    prime[j] = i;
 
    for i in range(2, MAX):
        if (prime[i] == 0):
            prime[i] = i;
            primes.append(i);
         
# def to count sub-arrays whose product
# is divisible by k
def countSubarrays(arr, n, k):
    global k_cnt, current_map, cnts
     
    # Special case
    if (k == 1) :
        print(int((1 * n * (n + 1)) / 2));
        return 0;
     
 
    k_primes = [];
 
    for p in primes:
        while (k % p == 0) :
            k_primes.append(p);
            k = int(k / p);
         
    # If k is prime and is more than 10^6
    if (k > 1) :
        k_primes.append(k);
     
 
    for num in k_primes:
        if ((num) not in k_cnt):
            k_cnt[num] = 0;
        k_cnt[num] += 1
     
 
    # Two pointers initialized
    l = 0
    r = 0;
 
    ans = 0;
 
    while (r < n) :
 
        # Add rth element to the current segment
        for it, p in k_cnt.items():
 
            # p = prime factor of k
 
            while (arr[r] % p == 0) :
                if (p not in current_map):
                    current_map[p] = 0;
                current_map[p] += 1
                if p not in cnts[r]:
                    cnts[r][p] = 0;
                cnts[r][p] += 1
                arr[r] = int(arr[r] / p);
             
         
 
        # Check if current sub-array's product
        # is divisible by k
        flag = 0;
        for it, p in k_cnt.items():
             
            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 not (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 it, p in (k_cnt).items():
                p = it;
                current_map[p] -= cnts[l][p];
             
 
            l += 1
         
        else:
            r += 1
         
    return ans;
 
# Driver code
arr = [ 6, 2, 8 ];
n = len(arr);
k = 4;
sieve();
print(countSubarrays(arr, n, k));
 
 
# This code is contributed by phasing17


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  static int MAX = 100002;
 
  // Vector to store primes
  static List<int> primes = new List<int>();
 
  // 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
  static Dictionary<int, int> k_cnt = new Dictionary<int, int>();
  static Dictionary<int, int> current_map = new Dictionary<int, int>();
  static List<Dictionary<int, int>> cnts = new List<Dictionary<int, int>>();
 
 
  // Function to store primes in
  // the vector primes
  static void sieve()
  {
 
    List<int> prime = new List<int>();
    for (int i = 0; i < MAX; i++)
      prime.Add(0);
    prime[0] = 1;
    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.Add(i);
      }
    }
  }
 
  // Function to count sub-arrays whose product
  // is divisible by k
  static int countSubarrays(int[] arr, int n, int k)
  {
 
    // Special case
    if (k == 1) {
      Console.WriteLine((int)((1 * n * (n + 1)) / 2));
      return 0;
    }
 
    List<int> k_primes = new List<int>();
 
    foreach (var p in primes) {
      while (k % p == 0) {
        k_primes.Add(p);
        k /= p;
      }
    }
 
    // If k is prime and is more than 10^6
    if (k > 1) {
      k_primes.Add(k);
    }
 
    foreach (var num in k_primes) {
      if (!k_cnt.ContainsKey(num))
        k_cnt[num] = 0;
      k_cnt[num]++;
    }
 
    // Two pointers initialized
    int l = 0;
    int r = 0;
 
    int ans = 0;
 
    while (r < n) {
 
      // Add rth element to the current segment
      foreach (var entry in k_cnt) {
 
        int it = entry.Key;
        int p = entry.Value;
        // p = prime factor of k
 
        while (arr[r] % p == 0) {
          if (!current_map.ContainsKey(p))
            current_map[p] = 0;
          current_map[p]++;
          if (!cnts[r].ContainsKey(p))
            cnts[r][p] = 0;
          cnts[r][p]++;
          arr[r] = (int)(arr[r] / p);
        }
      }
 
      // Check if current sub-array's product
      // is divisible by k
      int flag = 0;
      foreach (var entry in k_cnt) {
 
        int it = entry.Key;
        int p = entry.Value;
        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 == 0) {
 
        // flag = 0 means that after adding rth element
        // segment's product is divisible by k
        ans += n - r;
 
        // Eliminate 'l' from the current segment
        foreach (var entry in k_cnt) {
 
          int it = entry.Key;
          int p = entry.Value;
          p = it;
          current_map[p] -= cnts[l][p];
        }
 
        l++;
      }
      else {
        r++;
      }
    }
 
    return ans;
  }
 
 
  // Driver code
  public static void Main(string[] args)
  {
    for (int i = 0; i < MAX; i++)
      cnts.Add(new Dictionary<int, int>());
 
 
    int[] arr = { 6, 2, 8 };
    int n = arr.Length;
    int k = 4;
    sieve();
    Console.WriteLine(countSubarrays(arr, n, k));
  }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript implementation of the approach
let MAX = 100002
 
// Vector to store primes
let 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
let k_cnt = {};
let current_map = {};
let cnts = new Array(MAX);
for (var i = 0; i < MAX; i++)
    cnts[i] = {}
 
// Function to store primes in
// the vector primes
function sieve()
{
 
    let prime = new Array(MAX).fill(0);
    prime[0] = prime[1] = 1;
    for (var i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            for (var j = i * 2; j < MAX; j += i) {
                if (prime[j] == 0) {
                    prime[j] = i;
                }
            }
        }
    }
 
    for (var i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            prime[i] = i;
            primes.push(i);
        }
    }
}
 
// Function to count sub-arrays whose product
// is divisible by k
function countSubarrays(arr, n, k)
{
 
    // Special case
    if (k == 1) {
        console.log(Math.floor((1 * n * (n + 1)) / 2));
        return 0;
    }
 
    let k_primes = [];
 
    for (var p of primes) {
        while (k % p == 0) {
            k_primes.push(p);
            k = Math.floor(k / p);
        }
    }
 
    // If k is prime and is more than 10^6
    if (k > 1) {
        k_primes.push(k);
    }
 
    for (var num of k_primes) {
        if (!k_cnt.hasOwnProperty(num))
            k_cnt[num] = 0;
        k_cnt[num]++;
    }
 
    // Two pointers initialized
    var l = 0, r = 0;
 
    var ans = 0;
 
    while (r < n) {
 
        // Add rth element to the current segment
        for (var [it, p] of Object.entries(k_cnt)) {
 
            // p = prime factor of k
 
            while (arr[r] % p == 0) {
                if (!current_map.hasOwnProperty(p))
                    current_map[p] = 0;
                current_map[p]++;
                if (!cnts[r].hasOwnProperty(p))
                    cnts[r][p] = 0;
                cnts[r][p]++;
                arr[r] = Math.floor(arr[r] / p);
            }
        }
 
        // Check if current sub-array's product
        // is divisible by k
        let flag = 0;
        for (var [it, p] of Object.entries(k_cnt)) {
             
            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 (var [it, p] of Object.entries(k_cnt)) {
                p = it;
                current_map[p] -= cnts[l][p];
            }
 
            l++;
        }
        else {
            r++;
        }
    }
 
    return ans;
}
 
 
// Driver code
let arr = [ 6, 2, 8 ];
let n = arr.length;
let k = 4;
sieve();
console.log(countSubarrays(arr, n, k));
 
// This code is contributed by phasing17


Output: 

4

 



Last Updated : 09 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads