Total number of subsets in which the product of the elements is even
Last Updated :
09 Sep, 2022
Given an array arr[] of integer elements, the task is to find the total number of sub-sets of arr[] in which the product of the elements is even.
Examples:
Input: arr[] = {2, 2, 3}
Output: 6
All possible sub-sets are {2}, {2}, {2, 2}, {2, 3}, {2, 3} and {2, 2, 3}
Input: arr[] = {3, 3, 3}
Output: 6
Approach: We already know that:
- Even * Even = Even
- Odd * Even = Even
- Odd * Odd = Odd
Now, we need to count the total subsets in which at least a single even element is present in order for the product of the elements to be even.
Now, Total number of sub-sets having at least one even element = Total possible sub-sets of n – Total sub-sets having all odd elements
i.e. (2n – 1) – (2totalOdd – 1)
Below is the implementation of the above approach:
C++
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void find( int a[], int n)
{
int count_odd = 0;
for ( int i = 0; i < n ; i++)
{
if (i % 2 != 0)
count_odd += 1;
}
int result = pow (2, n) - 1 ;
result -= ( pow (2, count_odd) - 1) ;
cout << result << endl;
}
int main()
{
int a[] = {2, 2, 3} ;
int n = sizeof (a)/ sizeof (a[0]) ;
find(a,n);
return 0;
}
|
Java
class GFG {
static void find( int a[], int n) {
int count_odd = 0 ;
for ( int i = 0 ; i < n; i++) {
if (i % 2 != 0 ) {
count_odd += 1 ;
}
}
int result = ( int ) (Math.pow( 2 , n) - 1 );
result -= (Math.pow( 2 , count_odd) - 1 );
System.out.println(result);
}
public static void main(String[] args) {
int a[] = { 2 , 2 , 3 };
int n = a.length;
find(a, n);
}
}
|
Python3
import math as ma
def find(a):
count_odd = 0
for i in a:
if (i % 2 ! = 0 ):
count_odd + = 1
result = pow ( 2 , len (a)) - 1
result = result - ( pow ( 2 , count_odd) - 1 )
print (result)
a = [ 2 , 2 , 3 ]
find(a)
|
C#
using System;
public class GFG {
static void find( int []a, int n) {
int count_odd = 0;
for ( int i = 0; i < n; i++) {
if (i % 2 != 0) {
count_odd += 1;
}
}
int result = ( int ) (Math.Pow(2, n) - 1);
result -= ( int )(Math.Pow(2, count_odd) - 1);
Console.Write(result);
}
public static void Main() {
int []a = {2, 2, 3};
int n = a.Length;
find(a, n);
}
}
|
PHP
<?php
function find(& $a , $n )
{
$count_odd = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $i % 2 != 0)
$count_odd += 1;
}
$result = pow(2, $n ) - 1 ;
$result -= (pow(2, $count_odd ) - 1) ;
echo $result . "\n" ;
}
$a = array (2, 2, 3) ;
$n = sizeof( $a )/sizeof( $a [0]) ;
find( $a , $n );
return 0;
?>
|
Javascript
<script>
function find(a, n)
{
var count_odd = 0;
for ( var i = 0; i < n ; i++)
{
if (i % 2 != 0)
count_odd += 1;
}
var result = Math.pow(2, n) - 1 ;
result -= (Math.pow(2, count_odd) - 1) ;
document.write( result );
}
var a = [2, 2, 3];
var n = a.length;
find(a,n);
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...