📜  计算乘积等于给定素数幂的子数组

📅  最后修改于: 2021-05-17 02:31:47             🧑  作者: Mango

给定大小为N的数组arr []和整数M ,任务是计算其元素乘积等于M的幂的子数组的数量,其中M是质数。

例子:

天真的方法:最简单的方法是生成数组arr []的所有可能的子数组,并为每个子数组检查其乘积是否为M的幂。如果发现为真,则将此类子数组的计数增加1。最后,打印获得的计数。

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

高效方法:最佳思想是基于这样一个事实,即任何子阵列的乘积等于M的幂,由于M是质数,所以子阵列中的所有元素也必须具有M的幂。请按照以下步骤解决给定的问题:

  • 初始化变量,例如ans ,以存储所需子数组的数量
  • 初始化一个变量,例如cnt ,以存储作为M的幂的连续数字的计数。
  • 使用变量i遍历索引[0,N – 1]范围内的数组,并执行以下操作:
    • 如果arr [i]M的幂。将cnt递增1。更新ans = ans +(cnt *(cnt – 1))/ 2
    • 否则,更新cnt = 0。
  • 完成上述步骤后,打印cnt的值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if y
// is a power of m or not
bool isPower(int m, int y)
{
    // Calculate log y base m and store
    // it in a variable with integer datatype
    int res1 = log(y) / log(m);
 
    // Calculate log y base m and store
    // it in a variable with double datatype
    double res2 = log(y) / log(m);
 
    // If res1 and res2 are equal, return
    // True. Otherwise, return false
    return (res1 == res2);
}
 
// Function to count the number of subarrays
// having product of elements equal to a
// power of m, where m is a prime number
int numSub(int arr[], int n, int m)
{
    // Stores the count of
    // subarrays required
    int ans = 0;
 
    // Stores current sequence of
    // consecutive array elements
    // which are a multiple of m
    int cnt = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // If arr[i] is a power of M
        if (isPower(m, arr[i])) {
 
            // Increment cnt
            cnt++;
 
            // Update ans
            ans += (cnt * (cnt - 1)) / 2;
        }
        else {
 
            // Update cnt
            cnt = 0;
        }
    }
 
    // Return the count
    // of subarrays
    return ans;
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { 1, 1, 1, 3 };
    int m = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << numSub(arr, n, m);
 
    return 0;
}


Java
// Java code of above approach
import java.util.*;
class GFG
{
   
// Function to check if y
// is a power of m or not
static boolean isPower(int m, int y)
{
   
    // Calculate log y base m and store
    // it in a variable with integer datatype
    int res1 = (int)Math.log(y) / (int)Math.log(m);
  
    // Calculate log y base m and store
    // it in a variable with double datatype
    double res2 = (int)Math.log(y) / (int)Math.log(m);
  
    // If res1 and res2 are equal, return
    // True. Otherwise, return false
    return (res1 == res2);
}
  
// Function to count the number of subarrays
// having product of elements equal to a
// power of m, where m is a prime number
static int numSub(int arr[], int n, int m)
{
   
    // Stores the count of
    // subarrays required
    int ans = 0;
  
    // Stores current sequence of
    // consecutive array elements
    // which are a multiple of m
    int cnt = 0;
  
    // Traverse the array
    for (int i = 0; i < n; i++) {
  
        // If arr[i] is a power of M
        if (isPower(m, arr[i])) {
  
            // Increment cnt
            cnt++;
  
            // Update ans
            ans += (cnt * (cnt - 1)) / 2;
        }
        else {
  
            // Update cnt
            cnt = 0;
        }
    }
  
    // Return the count
    // of subarrays
    return ans;
}
  
    // Driver code
   public static void main(String[] args)
    {
      
     // Input
    int arr[] = { 1, 1, 1, 3 };
    int m = 3;
    int n = arr.length;
  
   System.out.println(numSub(arr, n, m));
    }
}
 
// This code is contributed by offbeat


Python3
# Python 3 program for the above approach
from math import log
 
# Function to check if y
# is a power of m or not
def isPower(m, y):
   
    # Calculate log y base m and store
    # it in a variable with integer datatype
    res1 = log(y) // log(m)
 
    # Calculate log y base m and store
    # it in a variable with double datatype
    res2 = log(y) // log(m)
 
    # If res1 and res2 are equal, return
    # True. Otherwise, return false
    return (res1 == res2)
 
# Function to count the number of subarrays
# having product of elements equal to a
# power of m, where m is a prime number
def numSub(arr, n, m):
   
    # Stores the count of
    # subarrays required
    ans = 0
 
    # Stores current sequence of
    # consecutive array elements
    # which are a multiple of m
    cnt = 0
 
    # Traverse the array
    for i in range(n):
       
        # If arr[i] is a power of M
        if (isPower(m, arr[i])):
 
            # Increment cnt
            cnt += 1
 
            # Update ans
            ans += (cnt * (cnt - 1)) // 2
 
        else:
            # Update cnt
            cnt = 0
 
    # Return the count
    # of subarrays
    return ans
 
# Driver Code
if __name__ == '__main__':
   
    # Input
    arr =  [1, 1, 1, 3]
    m = 3
    n = len(arr)
    print(numSub(arr, n, m))
     
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if y
// is a power of m or not
static bool isPower(int m, int y)
{
     
    // Calculate log y base m and store
    // it in a variable with integer datatype
    int res1 = (int)Math.Log(y) / (int)Math.Log(m);
 
    // Calculate log y base m and store
    // it in a variable with double datatype
    double res2 = (int)Math.Log(y) / (int)Math.Log(m);
 
    // If res1 and res2 are equal, return
    // True. Otherwise, return false
    return (res1 == res2);
}
 
// Function to count the number of subarrays
// having product of elements equal to a
// power of m, where m is a prime number
static int numSub(int[] arr, int n, int m)
{
 
    // Stores the count of
    // subarrays required
    int ans = 0;
 
    // Stores current sequence of
    // consecutive array elements
    // which are a multiple of m
    int cnt = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
 
        // If arr[i] is a power of M
        if (isPower(m, arr[i]))
        {
             
            // Increment cnt
            cnt++;
 
            // Update ans
            ans += (cnt * (cnt - 1)) / 2;
        }
        else
        {
             
            // Update cnt
            cnt = 0;
        }
    }
 
    // Return the count
    // of subarrays
    return ans;
}
 
// Driver code
public static void Main()
{
 
    // Input
    int[] arr = { 1, 1, 1, 3 };
    int m = 3;
    int n = arr.Length;
 
    Console.Write(numSub(arr, n, m));
}
}
 
// This code is contributed by subhammahato348


Javascript


输出:
10

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