📜  具有乘积为完美立方体的子阵列的数量

📅  最后修改于: 2021-04-17 15:20:54             🧑  作者: Mango

给定一个由N个正整数组成的数组arr [] ,任务是计算其元素乘积等于一个完美立方体的子数组的数量。

例子:

天真的方法:最简单的方法是从给定的数组生成所有可能的子数组,并对那些其子数组元素乘积是一个完美立方体的子数组进行计数。检查所有子阵列后,打印获得的计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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.


C++14
// C++ program for the above approach
#include 
using namespace std;
#define MAX 1e5
 
// Function to store the prime
// factorization of a number
void primeFactors(vector& 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 v(MAX, 0);
 
    // Stores the occurrences
    // of the prime factors
    map, 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 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


输出:
6

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:还可以通过遍历数组并相应地计算完美立方体的方式,在HashMap中将模数为3的素因子存储起来,从而优化上述方法。请按照以下步骤解决问题:

  • 初始化变量ans来存储所需的结果,并初始化数组V并使用0来存储给定数组arr []中每个元素的素数模3的频率。
  • 初始化一个哈希表,例如M,以存储质数因子当前状态的频率,并在哈希表中将V递增1
  • 使用变量遍历数组arr []执行以下步骤:
    • arr [i]的质数模mod 3的频率存储在V中
    • 通过以MⅤ的频率递增ANS的值,然后递增Vm的值。
  • 完成上述步骤后。打印出ans的值作为结果。

下面是上述方法的实现:

C++ 14

// C++ program for the above approach
#include 
using namespace std;
#define MAX 1e5
 
// Function to store the prime
// factorization of a number
void primeFactors(vector& 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 v(MAX, 0);
 
    // Stores the occurrences
    // of the prime factors
    map, 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 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
输出:
6

时间复杂度: O(N 3/2 )
辅助空间: O(N)