Count sub-arrays whose product is divisible by k
Last Updated :
11 Jul, 2025
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++
// 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>
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>
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>
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
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem