The Wayback Machine - https://web.archive.org/web/20210304182421/https://www.geeksforgeeks.org/count-of-subarrays-having-product-as-a-perfect-cube/
Skip to content
Related Articles

Related Articles

Count of subarrays having product as a perfect cube
  • Last Updated : 02 Mar, 2021

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


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.


 
 

Output: 

6

 

 

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


 
 

Output: 

6

 

 

Time Complexity: O(N3/2)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :