📌  相关文章
📜  计算甚至通过替换来制造数组元素的乘积的方法

📅  最后修改于: 2021-05-19 18:20:33             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是计算即使通过任意多次替换数组元素来生成数组元素的乘积的方法数。由于计数可能非常大,请以10 9 +7为模数打印计数。

例子:

方法:想法是使用贪婪方法解决此问题。
请按照以下步骤解决问题:

  • 为了使数组的乘积均匀,必须至少存在一个偶数数组元素。
  • 遍历数组。对于每个数组元素,都会出现以下两种情况:
    • 如果阵列由单个元件的唯一,则只有一个方式中存在,使该阵列的产物均匀。
    • 否则,为2 N – 1路。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count ways to make
// product of given array even.
void makeProductEven(int arr[], int N)
{
    int m = 1000000007, ans = 1;
 
    // Calculate 2 ^ N
    for (int i = 0; i < N; i++)
    {
        ans = (ans * 2) % m;
    }
 
    // Print the answer
    cout << ans - 1;
}
 
// Driver Code
int main()
{
   
    // Given array
    int arr[] = { 1, 3 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
    makeProductEven(arr, N);
    return 0;
}


Java
// Java program for above approach
/*package whatever //do not write package name here */
import java.io.*;
class GFG
{
 
  // Method to count ways to make
  // product of given array even.
  static void makeProductEven(int arr[], int N)
  {
    int m = 1000000007, ans = 1;
 
    // Calculate 2 ^ N
    for (int i = 0; i < N; i++)
    {
      ans = (ans * 2) % m;
    }
 
    // Print the answer
    System.out.println(ans - 1);
  }
  public static void main(String[] args)
  {
 
    // Given array
    int arr[] = { 1, 3 };
 
    // Size of the array
    int N = arr.length;
    makeProductEven(arr, N);
  }
}
 
// This code is contributed by shubham agrawal


Python3
# Python3 program for the above approach
 
# Function to count ways to make
# product of given array even.
def makeProductEven(arr, N) :
    m = 1000000007; ans = 1;
 
    # Calculate 2 ^ N
    for i in range(N) :
        ans = (ans * 2) % m;
 
    # Print the answer
    print(ans - 1);
 
# Driver Code
if __name__ == "__main__" :
 
    # Given array
    arr = [ 1, 3 ];
 
    # Size of the array
    N = len(arr);
 
    makeProductEven(arr, N);
 
    # This code is contributed by AnkThon


C#
// C# program for above approach
/*package whatever //do not write package name here */
using System;
public class GFG
{
 
  // Method to count ways to make
  // product of given array even.
  static void makeProductEven(int []arr, int N)
  {
    int m = 1000000007, ans = 1;
 
    // Calculate 2 ^ N
    for (int i = 0; i < N; i++)
    {
      ans = (ans * 2) % m;
    }
 
    // Print the answer
    Console.WriteLine(ans - 1);
  }
   
  // Driver code
  public static void Main(String[] args)
  {
 
    // Given array
    int []arr = { 1, 3 };
 
    // Size of the array
    int N = arr.Length;
    makeProductEven(arr, N);
  }
}
 
// This code is contributed by shikhasingrajput


输出
3

时间复杂度: O(N)

辅助空间: O(1)