Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count of subsets having sum of min and max element less than K
Next article icon

Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0

Last Updated : 16 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1.

Examples:

Input: N = 3,  K = 2
Output: 9
Explanation:  22 – 1 = 3, so elements of  arrays should be between 0 to 3. All possible arrays are- [3, 3, 0],  [1, 2, 3], [3, 0, 3], [0, 3, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] Bitwise AND of all the arrays is 0 & also the sum = 6 is maximum 
Input: N = 2, K = 2
Output: 4
Explanation:  All possible arrays are –  [3, 0], [0, 3], [1, 2], [2, 1]

 

Approach: To better understand the approach, refer to the steps below:

  • As the maximum possible element is (2K – 1) and the size of the array is N so if all elements of the array are equal to the maximum element then the sum will be maximum i.e.  N * (2K – 1) = N * ( 20 + 21 + …………….. + 2K – 1 ). Keep in mind that there are K bits in ( 2K – 1) and all bits are set.
  • So now to make bitwise AND of all elements equal to 0 we have to unset each bit at least in one element. Also, we can not unset the same bit in more than 1 element because in that case sum will not be maximum.
  • After unsetting each bit in one element, the maximum possible Sum = N * ( 20 + 21 + ……… + 2K – 1 ) – ( 20 + 21 + ………. + 2K – 1 ) = (N * (2K -1 )) – (2K -1)= (N – 1) * (2K – 1).
  • Now the goal is to find all the ways through which we can unset all K bits in at least one element. You can see that for unsetting a single bit you have N options i.e. you can unset it in any one of N elements. So the total way for unsetting K bits will be NK. This is our final answer.

Illustration:

Let N = 3, K = 3
 

  • Make all elements of the array equal to 23 – 1 = 7. The array will be [7, 7, 7]. Take binary representation of all elements : [111, 111, 111].
  • Unset each bit in exactly one element. Suppose we unset the 3rd bit of the 1st element and the 1st two bits of the 2nd element. array becomes [110, 001, 111] = [6, 1, 7]. This is one of the valid arrays. You can generate all arrays in such a way.
  • The total number of arrays will be 33 = 27.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Iterative Function to calculate
// (x^y) in O(log y)
int power(int x, int y)
{
 
    // Initialize answer
    int res = 1;
 
    // Check till the number becomes zero
    while (y) {
 
        // If y is odd, multiply x with result
        if (y % 2 == 1)
            res = (res * x);
 
        // y = y/2
        y = y >> 1;
 
        // Change x to x^2
        x = (x * x);
    }
    return res;
}
 
// Driver Code
int main()
{
    int N = 3, K = 2;
    cout << power(N, K);
    return 0;
}
 
 

Java




// Java code for the above approach
import java.util.*;
public class GFG
{
 
  // Iterative Function to calculate
  // (x^y) in O(log y)
  static int power(int x, int y)
  {
 
    // Initialize answer
    int res = 1;
 
    // Check till the number becomes zero
    while (y > 0) {
 
      // If y is odd, multiply x with result
      if (y % 2 == 1)
        res = (res * x);
 
      // y = y/2
      y = y >> 1;
 
      // Change x to x^2
      x = (x * x);
    }
    return res;
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int N = 3, K = 2;
    System.out.print(power(N, K));
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Python3




# python3 program for the above approach
 
# Iterative Function to calculate
# (x^y) in O(log y)
def power(x, y):
 
    # Initialize answer
    res = 1
 
    # Check till the number becomes zero
    while (y):
 
        # If y is odd, multiply x with result
        if (y % 2 == 1):
            res = (res * x)
 
        # y = y/2
        y = y >> 1
 
        # Change x to x^2
        x = (x * x)
 
    return res
 
# Driver Code
if __name__ == "__main__":
 
    N = 3
    K = 2
    print(power(N, K))
 
    # This code is contributed by rakeshsahni
 
 

C#




// C# code to implement above approach
using System;
class GFG
{
   
  // Iterative Function to calculate
  // (x^y) in O(log y)
  static int power(int x, int y)
  {
 
    // Initialize answer
    int res = 1;
 
    // Check till the number becomes zero
    while (y > 0) {
 
      // If y is odd, multiply x with result
      if (y % 2 == 1)
        res = (res * x);
 
      // y = y/2
      y = y >> 1;
 
      // Change x to x^2
      x = (x * x);
    }
    return res;
  }
 
  // Driver code
  public static void Main()
  {
    int N = 3, K = 2;
    Console.Write(power(N, K));
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




  <script>
      // JavaScript code for the above approach
 
      // Iterative Function to calculate
      // (x^y) in O(log y)
      function power(x, y) {
 
          // Initialize answer
          let res = 1;
 
          // Check till the number becomes zero
          while (y) {
 
              // If y is odd, multiply x with result
              if (y % 2 == 1)
                  res = (res * x);
 
              // y = y/2
              y = y >> 1;
 
              // Change x to x^2
              x = (x * x);
          }
          return res;
      }
 
      // Driver Code
 
      let N = 3, K = 2;
      document.write(power(N, K));
 
// This code is contributed by Potta Lokesh
  </script>
 
 
Output
9

Time Complexity: O(logK)
Auxiliary Space: O(1)



Next Article
Count of subsets having sum of min and max element less than K
author
sachinjain74754
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • Bit Magic
  • C++ Programs
  • DSA
  • Mathematical
  • Bitwise-AND
  • Maths
Practice Tags :
  • Arrays
  • Bit Magic
  • Mathematical

Similar Reads

  • Count of subsets having sum of min and max element less than K
    Given an integer array arr[] and an integer K, the task is to find the number of non-empty subsets S such that min(S) + max(S) < K.Examples: Input: arr[] = {2, 4, 5, 7} K = 8 Output: 4 Explanation: The possible subsets are {2}, {2, 4}, {2, 4, 5} and {2, 5}Input:: arr[] = {2, 4, 2, 5, 7} K = 10 Ou
    5 min read
  • Count ways to place '+' and '-' in front of array elements to obtain sum K
    Given an array A[] consisting of N non-negative integers, and an integer K, the task is to find the number of ways '+' and '-' operators can be placed in front of elements of the array A[] such that the sum of the array becomes K. Examples: Input: A[] = {1, 1, 2, 3}, N = 4, K = 1Output: 3Explanation
    10 min read
  • Length of longest subset consisting of A 0s and B 1s from an array of strings
    Given an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s. Examples: Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subs
    15+ min read
  • Minimum sub-array such that number of 1's in concatenation of binary representation of its elements is at least K
    Given an array arr[] consisting of non-negative integers and an integer k. The task is to find the minimum length of any sub-array of arr[] such that if all elements of this sub-array are represented in binary notation and concatenated to form a binary string then number of 1's in the resulting stri
    10 min read
  • Count pairs whose Bitwise AND exceeds Bitwise XOR from a given array
    Given an array arr[] of size N, the task is to count the number of pairs from the given array such that the Bitwise AND (&) of each pair is greater than its Bitwise XOR(^). Examples : Input: arr[] = {1, 2, 3, 4} Output:1Explanation:Pairs that satisfy the given conditions are: (2 & 3) > (2
    6 min read
  • Count maximum number of disjoint pairs having one element not less than K times the other
    Given an array arr[] and a positive integer K, the task is to find the maximum count of disjoint pairs (arr[i], arr[j]) such that arr[j] ? K * arr[i]. Examples: Input: arr[] = { 1, 9, 4, 7, 3 }, K = 2Output: 2Explanation:There can be 2 possible pairs that can formed from the given array i.e., (4, 1)
    6 min read
  • Sum of Bitwise-OR of all subarrays of a given Array | Set 2
    Give an array of positive integers. The task is to find the total sum after performing the bitwise OR operation on all the sub-arrays of the given array. Examples: Input : arr[] = {1, 2, 3, 4, 5} Output : 71 Input : arr[] = {6, 5, 4, 3, 2} Output : 84 Explanation: Simple Approach: A simple approach
    12 min read
  • Minimize the maximum element of N subarrays of size K
    Given an array arr[] and two integers N and K, the task is to choose non-overlapping N subarrays of size K such that the maximum element of all subarrays is minimum.Note: If it is not possible to choose N such subarrays then return -1. Examples: Input: arr[] = {1, 10, 3, 10, 2}, N = 3, K = 1 Output:
    8 min read
  • Count total set bits in all numbers from 1 to n | Set 2
    Given a positive integer N, the task is to count the sum of the number of set bits in the binary representation of all the numbers from 1 to N.Examples: Input: N = 3 Output: 4 DecimalBinarySet Bit Count101121013112 1 + 1 + 2 = 4Input: N = 16 Output: 33 Recommended PracticeCount total set bitsTry It!
    11 min read
  • Count total set bits in all numbers from 1 to N | Set 3
    Given a positive integer N, the task is to count the total number of set bits in binary representation of all the numbers from 1 to N. Examples: Input: N = 3 Output: 4 setBits(1) + setBits(2) + setBits(3) = 1 + 1 + 2 = 4 Input: N = 6 Output: 9 Approach: Solution to this problem has been published in
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences