📜  前缀乘积数组

📅  最后修改于: 2021-09-05 11:45:14             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[]任务是从给定的数组中生成一个前缀乘积数组。

例子:

方法:
请按照以下步骤解决问题:

  • 从索引1N – 1迭代给定数组。
  • 为每个i索引计算 arr[i] = arr[i] * arr[i-1]。
  • 最后,打印前缀产品数组。

下面是上述方法的实现。

C++
// C++ Program to generate
// Prefix Product Array
#include 
using namespace std;
 
// Function to generate
// prefix product array
int prefixProduct(int a[],
                  int n)
{
    // Update the array
    // with the product of
    // prefixes
    for (int i = 1; i < n; i++) {
        a[i] = a[i] * a[i - 1];
    }
 
    // Print the array
    for (int j = 0; j < n; j++) {
        cout << a[j] << ", ";
    }
 
    return 0;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 6, 5, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
    prefixProduct(arr, N);
 
    return 0;
}


Java
// Java program to generate
// Prefix Product Array
class GFG{
 
// Function to generate
// prefix product array
static int prefixProduct(int []a, int n)
{
     
    // Update the array
    // with the product of
    // prefixes
    for(int i = 1; i < n; i++)
    {
       a[i] = a[i] * a[i - 1];
    }
 
    // Print the array
    for(int j = 0; j < n; j++)
    {
       System.out.print(a[j] + ", ");
    }
     
    return 0;
}
 
// Driver Code
public static void main (String[] args)
{
    int arr[] = new int[]{ 2, 4, 6, 5, 10 };
    int N = 5;
     
    prefixProduct(arr, N);
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 Program to generate
# Prefix Product Array
 
# Function to generate
# prefix product array
def prefixProduct(a, n):
 
    # Update the array
    # with the product of
    # prefixes
    for i in range(1, n):
        a[i] = a[i] * a[i - 1];
     
    # Print the array
    for j in range(0, n):
        print(a[j], end = ", ");
     
    return 0;
 
# Driver Code
arr = [ 2, 4, 6, 5, 10 ];
N = len(arr);
prefixProduct(arr, N);
 
# This code is contributed by Code_Mech


C#
// C# program to generate
// Prefix Product Array
using System;
class GFG{
 
// Function to generate
// prefix product array
static int prefixProduct(int []a, int n)
{
     
    // Update the array
    // with the product of
    // prefixes
    for(int i = 1; i < n; i++)
    {
        a[i] = a[i] * a[i - 1];
    }
 
    // Print the array
    for(int j = 0; j < n; j++)
    {
        Console.Write(a[j] + ", ");
    }
    return 0;
}
 
// Driver Code
public static void Main (string[] args)
{
    int []arr = new int[]{ 2, 4, 6, 5, 10 };
    int N = 5;
     
    prefixProduct(arr, N);
}
}
 
// This code is contributed by rock_cool


Javascript


输出:
2, 8, 48, 240, 2400

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

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