Count of subarrays having product as a perfect cube
Last Updated :
15 Feb, 2023
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays with product of its elements equal to a perfect cube.
Examples:
Input: arr[] = {1, 8, 4, 2}
Output: 6
Explanation:
The subarrays with product of elements equal to a perfect cube are:
- {1}. Therefore, product of subarray = 1 (= (1)3).
- {1, 8}. Therefore, product of subarray = 8 ( = 23).
- {8}. Therefore, product of subarray = 8 = (23).
- {4, 2}. Therefore, product of subarray = 8 (= 23).
- {8, 4, 2}. Therefore, product of subarray = 64 (= 43).
- {1, 8, 4, 2}. Therefore, product of subarray = 64 (= 43).
Therefore, the total count is 6.
Input: arr[] = {10, 10,10}
Output: 1
Naive Approach: The simplest approach is to generate all possible subarrays from the given array and count those subarrays whose product of subarray elements is a perfect cube. After checking for all the subarrays, print the count obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if a number
// is perfect cube or not
bool perfectCube(int N)
{
int cube_root;
// Find the cube_root
cube_root = (int)round(pow(N, 1.0 / 3.0));
// If cube of cube_root is
// same as N, then return true
if (cube_root * cube_root * cube_root == N) {
return true;
}
// Otherwise
return false;
}
// Function to count subarrays
// whose product is a perfect cube
void countSubarrays(int a[], int n)
{
// Store the required result
int ans = 0;
// Traverse all the subarrays
for (int i = 0; i < n; i++) {
int prod = 1;
for (int j = i; j < n; j++) {
prod = prod * a[j];
// If product of the current
// subarray is a perfect cube
if (perfectCube(prod))
// Increment count
ans++;
}
}
// Print the result
cout << ans;
}
// Driver Code
int main()
{
int arr[] = { 1, 8, 4, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
countSubarrays(arr, N);
return 0;
}
Java
import java.util.*;
public class GFG
{
public static void main(String args[])
{
int arr[] = { 1, 8, 4, 2 };
int N = arr.length;
countSubarrays(arr, N);
}
// Function to count subarrays
// whose product is a perfect cube
static void countSubarrays(int a[], int n)
{
// Store the required result
int ans = 0;
// Traverse all the subarrays
for (int i = 0; i < n; i++)
{
int prod = 1;
for (int j = i; j < n; j++)
{
prod = prod * a[j];
// If product of the current
// subarray is a perfect cube
if (perfectCube(prod))
// Increment count
ans++;
}
}
// Print the result
System.out.println(ans);
}
// Function to check if a number
// is perfect cube or not
static boolean perfectCube(int N)
{
int cube_root;
// Find the cube_root
cube_root = (int)Math.round(Math.pow(N, 1.0 / 3.0));
// If cube of cube_root is
// same as N, then return true
if (cube_root * cube_root * cube_root == N)
{
return true;
}
// Otherwise
return false;
}
}
// This code is contributed by abhinavjain194.
Python3
# Python 3 program for the above approach
# Function to check if a number
# is perfect cube or not
def perfectCube(N):
# Find the cube_root
cube_root = round(pow(N, 1 / 3))
# If cube of cube_root is
# same as N, then return true
if (cube_root * cube_root * cube_root == N):
return True
# Otherwise
return False
# Function to count subarrays
# whose product is a perfect cube
def countSubarrays(a, n):
# Store the required result
ans = 0
# Traverse all the subarrays
for i in range(n):
prod = 1
for j in range(i, n):
prod = prod * a[j]
# If product of the current
# subarray is a perfect cube
if (perfectCube(prod)):
# Increment count
ans += 1
# Print the result
print(ans)
# Driver Code
if __name__ == "__main__":
arr = [1, 8, 4, 2]
N = len(arr)
countSubarrays(arr, N)
# This code is contributed by ukasp.
C#
// C# program to implement
// the above approach
using System;
public class GFG
{
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 1, 8, 4, 2 };
int N = arr.Length;
countSubarrays(arr, N);
}
// Function to count subarrays
// whose product is a perfect cube
static void countSubarrays(int[] a, int n)
{
// Store the required result
int ans = 0;
// Traverse all the subarrays
for (int i = 0; i < n; i++)
{
int prod = 1;
for (int j = i; j < n; j++)
{
prod = prod * a[j];
// If product of the current
// subarray is a perfect cube
if (perfectCube(prod))
// Increment count
ans++;
}
}
// Print the result
Console.Write(ans);
}
// Function to check if a number
// is perfect cube or not
static bool perfectCube(int N)
{
int cube_root;
// Find the cube_root
cube_root = (int)Math.Round(Math.Pow(N, 1.0 / 3.0));
// If cube of cube_root is
// same as N, then return true
if (cube_root * cube_root * cube_root == N)
{
return true;
}
// Otherwise
return false;
}
}
// This code is contributed by souravghosh0416.
JavaScript
<script>
// Function to count subarrays
// whose product is a perfect cube
function countSubarrays(a , n)
{
// Store the required result
var ans = 0;
// Traverse all the subarrays
for (i = 0; i < n; i++)
{
var prod = 1;
for (j = i; j < n; j++)
{
prod = prod * a[j];
// If product of the current
// subarray is a perfect cube
if (perfectCube(prod))
// Increment count
ans++;
}
}
// Print the result
document.write(ans);
}
// Function to check if a number
// is perfect cube or not
function perfectCube(N)
{
var cube_root;
// Find the cube_root
cube_root = parseInt(Math.round(Math.pow(N, 1.0 / 3.0)));
// If cube of cube_root is
// same as N, then return true
if (cube_root * cube_root * cube_root == N)
{
return true;
}
// Otherwise
return false;
}
var arr = [ 1, 8, 4, 2 ];
var N = arr.length;
countSubarrays(arr, N);
// This code is contributed by 29AjayKumar
</script>
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by storing the number of prime factors modulo 3 in a HashMap while traversing the array and count perfect cubes accordingly. Follow the steps below to solve the problem:
- Initialize a variable, say ans, to store the required result, and an array V with 0s to store the frequency of prime factors mod 3 for every element in the given array arr[].
- Initialize a Hashmap, say M, to store the frequency of the current state of prime factors and increment V by 1 in the HashMap.
- Traverse the array arr[] using the variable i perform the following steps:
- After completing the above steps. print the value of ans as the result.
Below is the implementation of the above approach:
C++14
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1e5
// Function to store the prime
// factorization of a number
void primeFactors(vector<int>& v, int n)
{
for (int i = 2; i * i <= n; i++) {
// If N is divisible by i
while (n % i == 0) {
// Increment v[i] by 1 and
// calculate it modulo by 3
v[i]++;
v[i] %= 3;
// Divide the number by i
n /= i;
}
}
// If the number is not equal to 1
if (n != 1) {
// Increment v[n] by 1
v[n]++;
// Calculate it modulo 3
v[n] %= 3;
}
}
// Function to count the number of
// subarrays whose product is a perfect cube
void countSubarrays(int arr[], int n)
{
// Store the required result
int ans = 0;
// Stores the prime
// factors modulo 3
vector<int> v(MAX, 0);
// Stores the occurrences
// of the prime factors
map<vector<int>, int> mp;
mp[v]++;
// Traverse the array, arr[]
for (int i = 0; i < n; i++) {
// Store the prime factors
// and update the vector v
primeFactors(v, arr[i]);
// Update the answer
ans += mp[v];
// Increment current state
// of the prime factors by 1
mp[v]++;
}
// Print the result
cout << ans;
}
// Driver Code
int main()
{
int arr[] = { 1, 8, 4, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
countSubarrays(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static int MAX = (int)(1e5);
// To store the arr as a Key in map
static class Key
{
int arr[];
Key(int arr[])
{
this.arr = arr;
}
@Override public int hashCode()
{
return 31 + Arrays.hashCode(arr);
}
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null ||
(getClass() != obj.getClass()))
return false;
Key other = (Key)obj;
if (!Arrays.equals(arr, other.arr))
return false;
return true;
}
}
// Function to store the prime
// factorization of a number
static void primeFactors(int v[], int n)
{
for(int i = 2; i * i <= n; i++)
{
// If N is divisible by i
while (n % i == 0)
{
// Increment v[i] by 1 and
// calculate it modulo by 3
v[i]++;
v[i] %= 3;
// Divide the number by i
n /= i;
}
}
// If the number is not equal to 1
if (n != 1)
{
// Increment v[n] by 1
v[n]++;
// Calculate it modulo 3
v[n] %= 3;
}
}
// Function to count the number of
// subarrays whose product is a perfect cube
static void countSubarrays(int arr[], int n)
{
// Store the required result
int ans = 0;
// Stores the prime
// factors modulo 3
int v[] = new int[MAX];
// Stores the occurrences
// of the prime factors
HashMap<Key, Integer> mp = new HashMap<>();
mp.put(new Key(v), 1);
// Traverse the array, arr[]
for(int i = 0; i < n; i++)
{
// Store the prime factors
// and update the vector v
primeFactors(v, arr[i]);
// Update the answer
ans += mp.getOrDefault(new Key(v), 0);
// Increment current state
// of the prime factors by 1
Key vv = new Key(v);
mp.put(vv, mp.getOrDefault(vv, 0) + 1);
}
// Print the result
System.out.println(ans);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 8, 4, 2 };
int N = arr.length;
countSubarrays(arr, N);
}
}
// This code is contributed by Kingash
Python3
from typing import List
from collections import defaultdict
MAX = (int)(1e5)
# To store the arr as a Key in map
class Key:
def __init__(self, arr):
self.arr = arr
def __hash__(self):
return 31 + hash(tuple(self.arr))
def __eq__(self, other):
return self.arr == other.arr
# Function to store the prime
# factorization of a number
def primeFactors(v: List[int], n: int):
for i in range(2, int(n ** 0.5) + 1):
# If N is divisible by i
while n % i == 0:
# Increment v[i] by 1 and
# calculate it modulo by 3
v[i] += 1
v[i] %= 3
# Divide the number by i
n /= i
# If the number is not equal to 1
if n != 1:
# Increment v[n] by 1
v[n] += 1
# Calculate it modulo 3
v[n] %= 3
# Function to count the number of
# subarrays whose product is a perfect cube
def countSubarrays(arr: List[int], n: int):
# Store the required result
ans = 0
# Stores the prime
# factors modulo 3
v = [0] * MAX
# Stores the occurrences
# of the prime factors
mp = defaultdict(int)
mp[Key(v)] = 1
# Traverse the array, arr[]
for i in range(n):
# Store the prime factors
# and update the vector v
primeFactors(v, arr[i])
# Update the answer
ans += mp[Key(v)]
# Increment current state
# of the prime factors by 1
vv = Key(v)
mp[vv] += 1
# Print the result
print(ans)
# Driver Code
arr = [1, 8, 4, 2]
N = len(arr)
countSubarrays(arr, N)
# This code is contributed by aadityaburujwale.
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static int MAX = (int)(1e5);
// To store the arr as a Key in map
class Key
{
int[] arr;
public Key(int[] arr)
{
this.arr = arr;
}
public override int GetHashCode()
{
return 31 + arr.GetHashCode();
}
public override bool Equals(object obj)
{
if (this == obj)
return true;
if (obj == null ||
(GetType() != obj.GetType()))
return false;
Key other = (Key)obj;
if (!arr.SequenceEqual(other.arr))
return false;
return true;
}
}
// Function to store the prime
// factorization of a number
static void primeFactors(int[] v, int n)
{
for (int i = 2; i * i <= n; i++)
{
// If N is divisible by i
while (n % i == 0)
{
// Increment v[i] by 1 and
// calculate it modulo by 3
v[i]++;
v[i] %= 3;
// Divide the number by i
n /= i;
}
}
// If the number is not equal to 1
if (n != 1)
{
// Increment v[n] by 1
v[n]++;
// Calculate it modulo 3
v[n] %= 3;
}
}
// Function to count the number of
// subarrays whose product is a perfect cube
static void countSubarrays(int[] arr, int n)
{
// Store the required result
int ans = 0;
// Stores the prime
// factors modulo 3
int[] v = new int[MAX];
// Stores the occurrences
// of the prime factors
Dictionary<Key, int> mp = new Dictionary<Key, int>();
mp[new Key(v)] = 1;
// Traverse the array, arr[]
for (int i = 0; i < n-1; i++)
{
// Store the prime factors
// and update the vector v
primeFactors(v, arr[i]);
// Update the answer
ans += mp.GetValueOrDefault(new Key(v), 0);
// Increment current state
// of the prime factors by 1
Key vv = new Key(v);
mp[vv] = mp.GetValueOrDefault(vv, 0) + 1;
}
// Print the result
Console.WriteLine(ans);
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 1, 8, 4, 2 };
int N = arr.Length;
countSubarrays(arr, N);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// JavaScript program for the above approach
function primeFactors(v, n) {
for (let i = 2; i * i <= n; i++) {
// If N is divisible by i
while (n % i == 0) {
// Increment v[i] by 1 and
// calculate it modulo by 3
v[i]++;
v[i] %= 3;
// Divide the number by i
n /= i;
}
}
// If the number is not equal to 1
if (n != 1) {
// Increment v[n] by 1
v[n]++;
// Calculate it modulo 3
v[n] %= 3;
}
}
// Function to count the number of
// subarrays whose product is a perfect cube
function countSubarrays(arr, n) {
// Store the required result
let ans = 0;
// Stores the prime
// factors modulo 3
let v = Array(1e5).fill(0);
// Stores the occurrences
// of the prime factors
let mp = new Map();
mp.set(v, 1);
// Traverse the array, arr[]
for (let i = 0; i < n; i++) {
// Store the prime factors
// and update the vector v
primeFactors(v, arr[i]);
// Update the answer
ans += mp.get(v)-1;
// Increment current state
// of the prime factors by 1
mp.set(v, mp.get(v) + 1);
}
// Print the result
console.log(ans);
}
// Driver Code
let arr = [1, 8, 4, 2];
let N = arr.length;
countSubarrays(arr, N);
// contributed by akashish__
Time Complexity: O(N3/2)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
Count of subarrays having sum as a perfect cube Given an array arr[], the task is to count the subarrays having sum as a perfect cube.Examples: Input: arr[] = {6, 10, 9, 2, 1, 113} Output: 3 Explanation: The subarrays with sum of elements equal to a perfect cube are: {1}. Therefore, sum of subarray = 1 (= 1^3).{6, 10, 9, 2}. Therefore, sum of sub
6 min read
Count subarrays having product equal to the power of a given Prime Number Given an array arr[] of size N and an integer M, the task is to count the number of subarrays having product of its elements equal to the power of M, where M is a prime number. Examples: Input: arr[] = {2, 2, 2, 2}, M = 2Output: 10Explanation: All possible non-empty subarrays having product equal to
8 min read
Number of subarrays having even product Given an array arr[] consisting of N integers, the task is to count the total number of subarrays having even product. Examples : Input: arr[] = { 7, 5, 4, 9 }Output: 6Explanation: There are total 6 subarrays { 4 }{ 5, 4 }{ 7, 5, 4 }{ 7, 5, 4, 9 }{ 5, 4, 9 }{ 4, 9 } Input: arr[] = { 1, 3, 5 }Output:
9 min read
Product of all Subarrays of an Array Given an array of integers arr of size N, the task is to print products of all subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64 Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [
7 min read
Count subsets in an array having product K Given an array arr[] of size N, the task is to find the count of all subsets from the given array whose product of is equal to K. Examples: Input: arr[] = { 1, 1, 2, 2, 3 }, K = 4 Output: 4 Explanation: Subsets with product equal to K(= 4) are: { { arr[0], arr[1], arr[2], arr[3] }, { arr[0], arr[2],
12 min read
Product of all Subarrays of an Array | Set 2 Given an array arr[] of integers of size N, the task is to find the products of all subarrays of the array.Examples: Input: arr[] = {2, 4} Output: 64 Explanation: Here, subarrays are {2}, {2, 4}, and {4}. Products of each subarray are 2, 8, 4. Product of all Subarrays = 64Input: arr[] = {1, 2, 3} Ou
5 min read