Saturday, 23 Oct 2021

# Count distinct ways to replace array elements such that product of the array becomes even

Count distinct ways to replace array elements such that product of the array becomes even
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: 3Explanation: All possible ways to make the product of array elements odd are as follows:Replace arr by any even integer. The array arr[] modifies to {even, 3}. Therefore, the product of the array = even * 3 = even.Replace arr by any even integer. The array arr[] modifies to {1, even}. Therefore, the product of the array = 1 * even = even.Replace arr and arr 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++

#include
#define M 1000000007
using namespace std;

long long power(long long x, long long y,
long long p)
{

long long res = 1;

while (y > 0) {

if (y & 1)
res = (res * x) % p;

y = y >> 1;

x = (x * x) % p;
}
return res;
}

int totalOperations(int arr[], int N)
{

long long res = power(2, N, M);

res–;

cout