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

📅  最后修改于: 2021-09-05 11:56:29             🧑  作者: 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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live