Count of N-size maximum sum Arrays with elements in range [0, 2^K – 1] and Bitwise AND equal to 0
Last Updated :
16 Jul, 2021
Given two positive integers N and K, the task is to find the number of arrays of size N such that each array element lies over the range [0, 2K – 1] with the maximum sum of array element having Bitwise AND of all array elements 0.
Examples:
Input: N = 2 K = 2
Output: 4
Explanation:
The possible arrays with maximum sum having the Bitwise AND of all array element as 0 {0, 3}, {3, 0}, {1, 2}, {2, 1}. The count of such array is 4.
Input: N = 5 K = 6
Output: 15625
Approach: The given problem can be solved by observing the fact that as the Bitwise AND of the generated array should be 0, then for each i in the range [0, K – 1] there should be at least 1 element with an ith bit equal to 0 in its binary representation. Therefore, to maximize the sum of the array, it is optimal to have exactly 1 element with the ith bit unset.
Hence, for each of the K bits, there are NC1 ways to make it unset in 1 array element. Therefore, the resultant count of an array having the maximum sum is given by NK.
Below is the implementation of the approach :
C++
#include <bits/stdc++.h>
using namespace std;
int power( int x, unsigned int y)
{
int res = 1;
while (y > 0) {
if (y & 1)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
void countArrays( int N, int K)
{
cout << int (power(N, K));
}
int main()
{
int N = 5, K = 6;
countArrays(N, K);
return 0;
}
|
Java
public class GFG
{
static int power( int x, int y)
{
int res = 1 ;
while (y > 0 ) {
if (y% 2 != 0 )
res = res * x;
y = y >> 1 ;
x = x * x;
}
return res;
}
static void countArrays( int N, int K)
{
System.out.println(( int )(power(N, K)));
}
public static void main(String args[])
{
int N = 5 , K = 6 ;
countArrays(N, K);
}
}
|
Python3
def power(x, y):
res = 1
while (y > 0 ):
if (y & 1 ):
res = res * x
y = y >> 1
x = x * x
return res
def countArrays(N, K):
print (power(N, K))
N = 5 ;
K = 6 ;
countArrays(N, K)
|
C#
using System;
class GFG{
static int power( int x, int y)
{
int res = 1;
while (y > 0)
{
if (y % 2 != 0)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
static void countArrays( int N, int K)
{
Console.WriteLine(( int )(power(N, K)));
}
public static void Main()
{
int N = 5, K = 6;
countArrays(N, K);
}
}
|
Javascript
<script>
function power(x, y) {
let res = 1;
while (y > 0) {
if (y & 1)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
function countArrays(N, K) {
document.write(power(N, K));
}
let N = 5, K = 6;
countArrays(N, K);
</script>
|
Time Complexity: O(log K)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...