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
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Sum of Bitwise-OR of all Submatrices
Next article icon

Sum of bitwise AND of all subarrays

Last Updated : 11 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array.

Examples:  

Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0  Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0 Bit-wise AND of {8} = 8  Sum = 1 + 1 + 0 + 5 + 0 + 8 =  15  Input : arr[] =  {7, 1, 1, 5} Output : 20 

Simple Solution: A simple solution will be to generate all the sub-arrays, and sum up the AND values of all the sub-arrays. It will take linear time on average to find the AND value of a sub-array and thus, the overall time complexity will be O(n3).

Efficient Solution: For the sake of better understanding, let’s assume that any bit of an element is represented by the variable ‘i’, and the variable ‘sum’ is used to store the final sum.
The idea here is, we will try to find the number of AND values(sub-arrays with bit-wise and(&)) with ith bit set. Let us suppose, there is ‘Si‘ number of sub-arrays with ith bit set. For, ith bit, the sum can be updated as sum += (2i * S).
We will break the task into multiple steps. At each step, we will try to find the number of AND values with ith bit set. For this, we will simply iterate through the array and find the number of contiguous segments with ith bit set and their lengths. For, each such segment of length ‘l’, value of sum can be updated as sum += (2i * l * (l + 1))/2.
Since, for each bit, we are performing O(N) iterations and as there are at most log(max(A)) bits, the time complexity of this approach will be O(N*log(max(A)), assuming max(A) = maximum value in the array.

Below is the implementation of the above idea: 

C++




// CPP program to find sum of bitwise AND
// of all subarrays
 
#include <iostream>
#include <vector>
using namespace std;
 
// Function to find the sum of
// bitwise AND of all subarrays
int findAndSum(int arr[], int n)
{
    // variable to store
    // the final sum
    int sum = 0;
 
    // multiplier
    int mul = 1;
 
    for (int i = 0; i < 30; i++) {
        // variable to check if
        // counting is on
        bool count_on = 0;
 
        // variable to store the
        // length of the subarrays
        int l = 0;
 
        // loop to find the contiguous
        // segments
        for (int j = 0; j < n; j++) {
            if ((arr[j] & (1 << i)) > 0)
                if (count_on)
                    l++;
                else {
                    count_on = 1;
                    l++;
                }
 
            else if (count_on) {
                sum += ((mul * l * (l + 1)) / 2);
                count_on = 0;
                l = 0;
            }
        }
 
        if (count_on) {
            sum += ((mul * l * (l + 1)) / 2);
            count_on = 0;
            l = 0;
        }
 
        // updating the multiplier
        mul *= 2;
    }
 
    // returning the sum
    return sum;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 7, 1, 1, 5 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << findAndSum(arr, n);
 
    return 0;
}
 
 

Java




// Java program to find sum of bitwise AND
// of all subarrays
class GFG
{
     
// Function to find the sum of
// bitwise AND of all subarrays
static int findAndSum(int []arr, int n)
{
    // variable to store
    // the final sum
    int sum = 0;
 
    // multiplier
    int mul = 1;
 
    for (int i = 0; i < 30; i++)
    {
        // variable to check if
        // counting is on
        boolean count_on = false;
 
        // variable to store the
        // length of the subarrays
        int l = 0;
 
        // loop to find the contiguous
        // segments
        for (int j = 0; j < n; j++)
        {
            if ((arr[j] & (1 << i)) > 0)
                if (count_on)
                    l++;
                else
                {
                    count_on = true;
                    l++;
                }
 
            else if (count_on)
            {
                sum += ((mul * l * (l + 1)) / 2);
                count_on = false;
                l = 0;
            }
        }
 
        if (count_on)
        {
            sum += ((mul * l * (l + 1)) / 2);
            count_on = false;
            l = 0;
        }
 
        // updating the multiplier
        mul *= 2;
    }
 
    // returning the sum
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int []arr = { 7, 1, 1, 5 };
    int n = arr.length;
 
    System.out.println(findAndSum(arr, n));
}
}
 
// This code is contributed
// by Code_Mech.
 
 

Python3




# Python3 program to find Sum of
# bitwise AND of all subarrays
import math as mt
 
# Function to find the Sum of
# bitwise AND of all subarrays
def findAndSum(arr, n):
     
    # variable to store the final Sum
    Sum = 0
 
    # multiplier
    mul = 1
 
    for i in range(30):
         
        # variable to check if counting is on
        count_on = 0
 
        # variable to store the length
        # of the subarrays
        l = 0
 
        # loop to find the contiguous
        # segments
        for j in range(n):
 
            if ((arr[j] & (1 << i)) > 0):
                if (count_on):
                    l += 1
                else:
                    count_on = 1
                    l += 1
 
            elif (count_on):
                Sum += ((mul * l * (l + 1)) // 2)
                count_on = 0
                l = 0
             
        if (count_on):
            Sum += ((mul * l * (l + 1)) // 2)
            count_on = 0
            l = 0
         
        # updating the multiplier
        mul *= 2
     
    # returning the Sum
    return Sum
 
# Driver Code
arr = [7, 1, 1, 5]
 
n = len(arr)
 
print(findAndSum(arr, n))
 
# This code is contributed by Mohit Kumar
 
 

C#




// C# program to find sum of bitwise AND
// of all subarrays
using System;
 
class GFG
{
 
// Function to find the sum of
// bitwise AND of all subarrays
static int findAndSum(int []arr, int n)
{
    // variable to store
    // the final sum
    int sum = 0;
 
    // multiplier
    int mul = 1;
 
    for (int i = 0; i < 30; i++)
    {
        // variable to check if
        // counting is on
        bool count_on = false;
 
        // variable to store the
        // length of the subarrays
        int l = 0;
 
        // loop to find the contiguous
        // segments
        for (int j = 0; j < n; j++)
        {
            if ((arr[j] & (1 << i)) > 0)
                if (count_on)
                    l++;
                else
                {
                    count_on = true;
                    l++;
                }
 
            else if (count_on)
            {
                sum += ((mul * l * (l + 1)) / 2);
                count_on = false;
                l = 0;
            }
        }
 
        if (count_on)
        {
            sum += ((mul * l * (l + 1)) / 2);
            count_on = false;
            l = 0;
        }
 
        // updating the multiplier
        mul *= 2;
    }
 
    // returning the sum
    return sum;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 7, 1, 1, 5 };
    int n = arr.Length;
 
    Console.Write(findAndSum(arr, n));
}
}
 
// This code is contributed
// by Akanksha Rai
 
 

PHP




<?php
// PHP program to find sum of bitwise
// AND of all subarrays
 
// Function to find the sum of
// bitwise AND of all subarrays
function findAndSum($arr, $n)
{
    // variable to store the
    // final sum
    $sum = 0;
 
    // multiplier
    $mul = 1;
 
    for ($i = 0; $i < 30; $i++)
    {
         
        // variable to check if
        // counting is on
        $count_on = 0;
 
        // variable to store the
        // length of the subarrays
        $l = 0;
 
        // loop to find the contiguous
        // segments
        for ($j = 0; $j < $n; $j++)
        {
            if (($arr[$j] & (1 << $i)) > 0)
                if ($count_on)
                    $l++;
                else
                {
                    $count_on = 1;
                    $l++;
                }
 
            else if ($count_on)
            {
                $sum += (($mul * $l * ($l + 1)) / 2);
                $count_on = 0;
                $l = 0;
            }
        }
 
        if ($count_on)
        {
            $sum += (($mul * $l * ($l + 1)) / 2);
            $count_on = 0;
            $l = 0;
        }
 
        // updating the multiplier
        $mul *= 2;
    }
 
    // returning the sum
    return $sum;
}
 
// Driver Code
$arr = array( 7, 1, 1, 5 );
 
$n = sizeof($arr);
 
echo findAndSum($arr, $n);
 
// This code is contributed by Ryuga
?>
 
 

Javascript




<script>
 
// Javascript program to find sum of bitwise AND
// of all subarrays
 
// Function to find the sum of
// bitwise AND of all subarrays
function findAndSum(arr, n)
{
    // variable to store
    // the final sum
    var sum = 0;
 
    // multiplier
    var mul = 1;
 
    for (var i = 0; i < 30; i++) {
        // variable to check if
        // counting is on
        var count_on = 0;
 
        // variable to store the
        // length of the subarrays
        var l = 0;
 
        // loop to find the contiguous
        // segments
        for (var j = 0; j < n; j++) {
            if ((arr[j] & (1 << i)) > 0)
                if (count_on)
                    l++;
                else {
                    count_on = 1;
                    l++;
                }
 
            else if (count_on) {
                sum += ((mul * l * (l + 1)) / 2);
                count_on = 0;
                l = 0;
            }
        }
 
        if (count_on) {
            sum += ((mul * l * (l + 1)) / 2);
            count_on = 0;
            l = 0;
        }
 
        // updating the multiplier
        mul *= 2;
    }
 
    // returning the sum
    return sum;
}
 
// Driver Code
var arr = [ 7, 1, 1, 5 ];
var n = arr.length;
document.write( findAndSum(arr, n));
 
</script>
 
 
Output: 
20

 

Time Complexity: O(N*log(max(A))
Auxiliary Space: O(1)



Next Article
Sum of Bitwise-OR of all Submatrices

D

DivyanshuShekhar1
Improve
Article Tags :
  • Algorithms
  • Bit Magic
  • Competitive Programming
  • DSA
  • Mathematical
  • Bitwise-AND
Practice Tags :
  • Algorithms
  • Bit Magic
  • Mathematical

Similar Reads

  • Sum of bitwise OR of all subarrays
    Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array. Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
    5 min read
  • Sum of bitwise AND of all submatrices
    Given an NxN matrix, the task is to find the sum of bit-wise AND of all of its rectangular sub-matrices. Examples: Input : arr[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output : 36 Explanation: All the possible submatrices will have AND value 1. Since, there are 36 submatrices in total, ans = 36 Input
    13 min read
  • Sum of Bitwise-OR of all Submatrices
    Given a NxN matrix, the task is to find the sum of bit-wise OR of all of its rectangular sub-matrices.Examples: Input : arr[][] = {{1, 0, 0}, {0, 0, 0}, {0, 0, 0}} Output : 9 Explanation: All the submatrices starting from the index (0, 0) will have OR value as 1. Thus, ans = 9 Input : arr[][] = {{9,
    14 min read
  • Queries for Sum of Bitwise AND of all Subarrays in a Range
    Given an array arr[] of size N, the task is to answer a set of Q queries, each in the format of queries[i][0] and queries[i][1]. For each queries[i], find the sum of Bitwise AND of all subarrays whose elements lie in the range [queries[i][0], queries[i][1]]. Examples: Input: N = 3, arr[] = {1, 0, 2}
    12 min read
  • Sum of all subarrays of size K
    Given an array arr[] and an integer K, the task is to calculate the sum of all subarrays of size K. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3 Output: 6 9 12 15 Explanation: All subarrays of size k and their sum: Subarray 1: {1, 2, 3} = 1 + 2 + 3 = 6 Subarray 2: {2, 3, 4} = 2 + 3 + 4 = 9 Sub
    11 min read
  • Sum of XOR of all subarrays
    Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array. Examples: Input : arr[] = {1, 3, 7, 9, 8, 7} Output : 128 Input : arr[] = {3, 8, 13} Output : 46 Explanation for second test-case: XOR of {3} = 3 XOR of {3, 8} = 11 XOR of {3, 8, 13} = 6
    13 min read
  • Sum of all Subarrays
    Given an integer array arr[], find the sum of all sub-arrays of the given array. Examples: Input: arr[] = [1, 2, 3]Output: 20Explanation: {1} + {2} + {3} + {2 + 3} + {1 + 2} + {1 + 2 + 3} = 20 Input: arr[] = [1, 2, 3, 4]Output: 50 Naive Approach - O(n^2) Time and O(1) SpaceA simple solution is to ge
    6 min read
  • Bitwise OR of Bitwise AND of all subarrays of an array
    Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are: {1}, Bitwise AND is 1.{1, 2}, Bitwise AN
    7 min read
  • Sum of Bitwise And of all pairs in a given array
    Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
    13 min read
  • Bitwise OR of sum of all subsequences of an array
    Given an array arr[] of length N, the task is to find the Bitwise OR of the sum of all possible subsequences from the given array. Examples: Input: arr[] = {4, 2, 5}Output: 15Explanation: All subsequences from the given array and their corresponding sums:{4} - 4{2} - 2{5} - 5{4, 2} - 6{4, 5} - 9{2,
    6 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