Given an array arr[] consisting of N odd integers, the task is to count the different number of ways to make the product of all array elements even, by repeatedly changing any set of elements to any values. Since the count can be very large, print it to modulo 109 + 7.
Examples:
Input: arr[] = {1, 3}
Output: 3
Explanation: All possible ways to make the product of array elements odd are as follows:
Replace arr[0] by any even integer. The array arr[] modifies to {even, 3}. Therefore, the product of the array = even * 3 = even.
Replace arr[1] by any even integer. The array arr[] modifies to {1, even}. Therefore, the product of the array = 1 * even = even.
Replace arr[0] and arr[1] by even integers. Since both array elements become even, the product of the array becomes even. Therefore, the total number of distinct ways to make the array even is 3.Input: arr[] = {1, 2, 3, 4, 5}
Output: 31
Approach: The idea to solve the given problem is based on the observation that the product of an array is even only when at least one even element is present in the array. Therefore, the total number of distinct ways can be calculated by the number of distinct subsets of the given array.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> #define M 1000000007 using namespace std; // Function to find the value of (x^y) long long power(long long x, long long y, long long p) { // Stores the result long long res = 1; while (y > 0) { // If y is odd, then // multiply x with res if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // Update x x = (x * x) % p; } return res; } // Function to count the number of ways // to make the product of an array even // by replacing array elements int totalOperations(int arr[], int N) { // Find the value ( 2 ^ N ) % M long long res = power(2, N, M); // Exclude empty subset res--; // Print the answer cout << res; } // Driver Code int main() { int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); totalOperations(arr, N); return 0; } |
31
Time Complexity: O(log N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

