Count ways to make product of array elements even by replacements
Given an array arr[] consisting of N integers, the task is to count the number of ways to make the product of array elements even by replacing array elements any number of times. Since the count can be very large, print the count modulo 109+7.
Examples:
Input: arr[] = {1, 3}
Output: 3
Explanation:
Operation 1: Replacing arr[0] by 2. Therefore, arr[] modifies to {2, 3}. Product = 6.
Operation 2: Replacing arr[0] by 10. Therefore, arr[] modifies to {1, 10}, Product= 10.
Operation 3: Replacing arr[0] and arr[1] by 2. Therefore, arr[] modifies to {2, 2}, Product = 4.
Hence, 3 possible ways exists.
Input: arr[] = {3}
Output: 1
Approach: The idea is to use Greedy Approach to solve this problem.
Follow the steps below to solve the problem:
- In order to make the product of the array even, at least one even array element must exist.
- Traverse the array. For every array element, the following two situations arise:
- If the array consists of a single element only, then only a single way exists to make the product of the array even.
- Otherwise, 2N – 1 ways.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void makeProductEven( int arr[], int N)
{
int m = 1000000007, ans = 1;
for ( int i = 0; i < N; i++)
{
ans = (ans * 2) % m;
}
cout << ans - 1;
}
int main()
{
int arr[] = { 1, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
makeProductEven(arr, N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void makeProductEven( int arr[], int N)
{
int m = 1000000007 , ans = 1 ;
for ( int i = 0 ; i < N; i++)
{
ans = (ans * 2 ) % m;
}
System.out.println(ans - 1 );
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 };
int N = arr.length;
makeProductEven(arr, N);
}
}
|
Python3
def makeProductEven(arr, N) :
m = 1000000007 ; ans = 1
for i in range (N) :
ans = (ans * 2 ) % m
print (ans - 1 )
if __name__ = = "__main__" :
arr = [ 1 , 3 ]
N = len (arr)
makeProductEven(arr, N)
|
C#
using System;
public class GFG
{
static void makeProductEven( int []arr, int N)
{
int m = 1000000007, ans = 1;
for ( int i = 0; i < N; i++)
{
ans = (ans * 2) % m;
}
Console.WriteLine(ans - 1);
}
public static void Main(String[] args)
{
int []arr = { 1, 3 };
int N = arr.Length;
makeProductEven(arr, N);
}
}
|
Javascript
<script>
function makeProductEven(arr, N)
{
var m = 1000000007, ans = 1;
for ( var i = 0; i < N; i++)
{
ans = (ans * 2) % m;
}
document.write( ans - 1);
}
var arr = [ 1, 3 ];
var N = arr.length;
makeProductEven(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
19 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...