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 odd and even sum pairs in an array
Next article icon

Sum of XOR of all pairs in an array

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of n integers, find the sum of xor of all pairs of numbers in the array.

Examples :

Input : arr[] = {7, 3, 5}
Output : 12
7 ^ 3 = 4
3 ^ 5 = 6
7 ^ 5 = 2
Sum = 4 + 6 + 2
= 12

Input : arr[] = {5, 9, 7, 6}
Output : 47
5 ^ 9 = 12
9 ^ 7 = 14
7 ^ 6 = 1
5 ^ 7 = 2
5 ^ 6 = 3
9 ^ 6 = 15
Sum = 12 + 14 + 1 + 2 + 3 + 15
= 47

Naive Solution: A Brute Force approach is to run two loops and time complexity is O(n2).

C++




// A Simple C++ program to compute
// sum of bitwise OR of all pairs
#include <bits/stdc++.h>
using namespace std;
  
// Returns sum of bitwise OR
// of all pairs
int pairORSum(int arr[], int n)
{
    int ans = 0; // Initialize result
  
    // Consider all pairs (arr[i], arr[j) such that
    // i < j
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            ans += arr[i] ^ arr[j];
  
    return ans;
}
  
// Driver program to test above function
int main()
{
    int arr[] = { 5, 9, 7, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << pairORSum(arr, n) << endl;
    return 0;
}
 
 

Java




// A Simple Java program to compute
// sum of bitwise OR of all pairs
import java.io.*;
  
class GFG {
      
              
    // Returns sum of bitwise OR
    // of all pairs
    static int pairORSum(int arr[], int n)
    {
        // Initialize result
        int ans = 0; 
      
        // Consider all pairs (arr[i], arr[j) 
        // such that i < j
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                ans += arr[i] ^ arr[j];
      
        return ans;
    }
  
    // Driver program to test above function
    public static void main (String[] args) {
     
        int arr[] = { 5, 9, 7, 6 };
        int n = arr.length;
          
        System.out.println(pairORSum(arr,
                                arr.length));
    }
}
//This code is contributed by vt_m
 
 

Python3




# A Simple Python 3 program to compute
# sum of bitwise OR of all pairs
  
# Returns sum of bitwise OR
# of all pairs
def pairORSum(arr, n) :
    ans = 0     # Initialize result
  
    # Consider all pairs (arr[i], arr[j) 
    # such that i < j
    for i in range(0, n) :
          
        for j in range(i + 1, n) :
              
            ans = ans + (arr[i] ^ arr[j])
              
    return ans
      
  
# Driver Code
arr = [ 5, 9, 7, 6 ]
n = len(arr)
  
print(pairORSum(arr, n))
  
  
  
# This code is contributed by Nikita Tiwari.
 
 

C#




// A Simple C# program to compute
// sum of bitwise OR of all pairs
using System;
  
class GFG {
      
              
    // Returns sum of bitwise OR
    // of all pairs
    static int pairORSum(int []arr, int n)
    {
        // Initialize result
        int ans = 0; 
      
        // Consider all pairs (arr[i], arr[j) 
        // such that i < j
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                ans += arr[i] ^ arr[j];
      
        return ans;
    }
  
    // Driver program to test above function
    public static void Main () {
      
        int []arr = { 5, 9, 7, 6 };
        int n = arr.Length;
          
        Console.WriteLine(pairORSum(arr,
                                arr.Length));
    }
}
  
  
// This code is contributed by vt_m
 
 

Javascript




// A Simple Javascript program to compute
// sum of bitwise OR of all pairs
 
// Returns sum of bitwise OR
// of all pairs
const pairORSum = (arr, n) => {
    let ans = 0; // Initialize result
 
    // Consider all pairs (arr[i], arr[j) such that
    // i < j
    for (let i = 0; i < n; i++)
        for (let j = i + 1; j < n; j++)
            ans += arr[i] ^ arr[j];
 
    return ans;
}
 
// Driver program to test above function
let arr = [5, 9, 7, 6];
let n = arr.length;
document.write(pairORSum(arr, n));
 
// This code is contributed by rakeshsahni
 
 

PHP




<?php
// A Simple PHP program to compute
// sum of bitwise OR of all pairs
  
// Returns sum of bitwise OR
// of all pairs
function pairORSum($arr, $n)
{
      
    // Initialize result
    $ans = 0; 
  
    // Consider all pairs 
    // (arr[i], arr[j) such that
    // i < j
    for ( $i = 0; $i < $n; $i++)
        for ( $j = $i + 1; $j < $n; $j++)
            $ans += $arr[$i] ^ $arr[$j];
  
    return $ans;
}
  
    // Driver Code
    $arr = array( 5, 9, 7, 6 );
    $n = count($arr);
    echo pairORSum($arr, $n) ;
  
// This code is contributed by anuj_67.
  
?>
 
 
Output
47  

Efficient Solution: An Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits. Optimized solution will be to try bit manipulation. To implement the solution, we consider all bits which are 1 and which are 0 and store their count in two different variables. Next multiple those counts along with the power of 2 raised to that bit position. Do this for all the bit positions of the numbers. Their sum would be our answer.
How this actually works?
For example, look at the rightmost bit of all the numbers in the array. Suppose that numbers have a rightmost 0-bit, and b numbers have a 1-bit. Then out of the pairs, a*b of them will have 1 in the rightmost bit of the XOR. This is because there are a*b ways to choose one number that has a 0-bit and one that has a 1-bit. These bits will therefore contribute a*b towards the total of all the XORs.In general, when looking at the nth bit (where the rightmost bit is the 0th), count how many numbers have 0 (call this an) and how many have 1 (call this bn). The contribution towards the final sum will be an*bn*pow(2,n). You need to do this for each bit and sum all these contributions together.This can be done in O(kn) time, where k is the number of bits in the given values.

Explanation :  arr[] = { 7, 3, 5 }
7 = 1 1 1
3 = 0 1 1
5 = 1 0 1
For bit position 0 :
Bits with zero = 0
Bits with one = 3
Answer = 0 * 3 * 2 ^ 0 = 0

Similarly, for bit position 1 :
Bits with zero = 1
Bits with one = 2
Answer = 1 * 2 * 2 ^ 1 = 4

Similarly, for bit position 2 :
Bits with zero = 1
Bits with one = 2
Answer = 1 * 2 * 2 ^ 2 = 8
Final answer = 0 + 4 + 8 = 12

CPP




// An efficient C++ program to compute 
// sum of bitwise OR of all pairs
#include <bits/stdc++.h>
using namespace std;
  
// Returns sum of bitwise OR
// of all pairs
long long int sumXOR(int arr[], int n)
{
    long long int sum = 0;
    for (int i = 0; i < 32; i++) 
    {
        //  Count of zeros and ones
        int zc = 0, oc = 0; 
          
        // Individual sum at each bit position
        long long int idsum = 0; 
        for (int j = 0; j < n; j++)
        {
            if (arr[j] % 2 == 0)
                zc++;
            else
                oc++;
            arr[j] /= 2;
        }
          
        // calculating individual bit sum 
        idsum = oc * zc * (1 << i); 
  
        // final sum    
        sum += idsum; 
    }
    return sum;
}
  
int main()
{
    long long int sum = 0;
    int arr[] = { 5, 9, 7, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sum = sumXOR(arr, n);
    cout << sum;
    return 0;
}
 
 

Java




// An efficient Java program to compute 
// sum of bitwise OR of all pairs
import java.io.*;
  
class GFG {
      
    // Returns sum of bitwise OR
    // of all pairs
    static long sumXOR(int arr[], int n)
    {
        long sum = 0;
        for (int i = 0; i < 32; i++) 
        {
            // Count of zeros and ones
            int zc = 0, oc = 0; 
              
            // Individual sum at each bit position
            long idsum = 0; 
              
            for (int j = 0; j < n; j++)
            {
                if (arr[j] % 2 == 0)
                    zc++;
                      
                else
                    oc++;
                arr[j] /= 2;
            }
              
            // calculating individual bit sum 
            idsum = oc * zc * (1 << i); 
      
            // final sum 
            sum += idsum; 
        }
        return sum;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        long sum = 0;
        int arr[] = { 5, 9, 7, 6 };
        int n = arr.length;
          
        sum = sumXOR(arr, n);
        System.out.println(sum);
    }
}
  
// This code is contributed by Nikita Tiwari.
 
 

Python3




# An efficient Python3 program to compute 
# sum of bitwise OR of all pair
  
# Returns sum of bitwise OR
# of all pairs
def sumXOR( arr,  n):
      
    sum = 0
    for i in range(0, 32):
  
        #  Count of zeros and ones
        zc = 0
        oc = 0
           
        # Individual sum at each bit position
        idsum = 0
        for j in range(0, n):
            if (arr[j] % 2 == 0):
                zc = zc + 1
                  
            else:
                oc = oc + 1
            arr[j] = int(arr[j] / 2)
          
           
        # calculating individual bit sum 
        idsum = oc * zc * (1 << i)
   
        # final sum    
        sum = sum + idsum; 
      
    return sum
  
  
  
# driver function 
sum = 0
arr = [  5, 9, 7, 6 ]
n = len(arr)
sum = sumXOR(arr, n);
print (sum)
  
# This code is contributed by saloni1297
 
 

C#




// An efficient C# program to compute 
// sum of bitwise OR of all pairs
using System;
  
class GFG {
      
    // Returns sum of bitwise OR
    // of all pairs
    static long sumXOR(int []arr, int n)
    {
        long sum = 0;
        for (int i = 0; i < 32; i++) 
        {
            // Count of zeros and ones
            int zc = 0, oc = 0; 
              
            // Individual sum at each bit position
            long idsum = 0; 
              
            for (int j = 0; j < n; j++)
            {
                if (arr[j] % 2 == 0)
                    zc++;
                      
                else
                    oc++;
                arr[j] /= 2;
            }
              
            // calculating individual bit sum 
            idsum = oc * zc * (1 << i); 
      
            // final sum 
            sum += idsum; 
        }
        return sum;
    }
      
    // Driver Code
    public static void Main()
    {
        long sum = 0;
        int []arr = { 5, 9, 7, 6 };
        int n = arr.Length;
          
        sum = sumXOR(arr, n);
        Console.WriteLine(sum);
    }
}
  
// This code is contributed by vt_m.
 
 

JavaScript




<script>
    // An efficient JavaScript program to compute
    // sum of bitwise OR of all pairs
  
    // Returns sum of bitwise OR
    // of all pairs
    const sumXOR = (arr, n) => {
        let sum = 0;
        for (let i = 0; i < 32; i++) {
  
            // Count of zeros and ones
            let zc = 0, oc = 0;
  
            // Individual sum at each bit position
            let idsum = 0;
            for (let j = 0; j < n; j++) {
                if (arr[j] % 2 == 0)
                    zc++;
                else
                    oc++;
                arr[j] = parseInt(arr[j] / 2);
            }
  
            // calculating individual bit sum
            idsum = oc * zc * (1 << i);
  
            // final sum    
            sum += idsum;
        }
        return sum;
    }
  
    let sum = 0;
    let arr = [5, 9, 7, 6];
    let n = arr.length;
    sum = sumXOR(arr, n);
    document.write(sum);
  
    // This code is contributed by rakeshsahni
  
</script>
  
?>
 
 

PHP




<?php
// An efficient PHP program to compute 
// sum of bitwise OR of all pairs
  
// Returns sum of bitwise OR
// of all pairs
function sumXOR($arr, $n)
{
    $sum = 0;
    for ($i = 0; $i < 32; $i++) 
    {
        // Count of zeros and ones
        $zc = 0; $oc = 0; 
          
        // Individual sum at each
        // bit position
        $idsum = 0; 
        for ($j = 0; $j < $n; $j++)
        {
            if ($arr[$j] % 2 == 0)
                $zc++;
            else
                $oc++;
                  
            $arr[$j] /= 2;
        }
          
        // calculating individual bit sum 
        $idsum = $oc * $zc * (1 << $i); 
  
        // final sum 
        $sum += $idsum; 
    }
      
    return $sum;
}
  
// Driver code
    $sum = 0;
    $arr = array( 5, 9, 7, 6 );
    $n = count($arr);
    $sum = sumXOR($arr, $n);
    echo $sum;
  
// This code is contributed by anuj_67
 
 

Output:

47


Next Article
Count of odd and even sum pairs in an array

P

premkagrani
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • 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
  • XOR of Sum of every possible pair of an array
    Given an array A of size n. the task is to generate a new sequence B with size N^2 having elements sum of every pair of array A and find the xor value of the sum of all the pairs formed. Note: Here (A[i], A[i]), (A[i], A[j]), (A[j], A[i]) all are considered as different pairs. Examples: Input: arr[]
    5 min read
  • Find XOR sum of Bitwise AND of all pairs from given two Arrays
    Given two arrays A and B of sizes N and M respectively, the task is to calculate the XOR sum of bitwise ANDs of all pairs of A and B Examples: Input: A={3, 5}, B={2, 3}, N=2, M=2Output:0Explanation:The answer is (3&2)^(3&3)^(5&2)^(5&3)=1^3^0^2=0. Input: A={1, 2, 3}, B={5, 6}, N=3, M=
    9 min read
  • Sum of XOR of all sub-arrays of length K
    Given an array of length n ( n > k), we have to find the sum of xor of all the elements of the sub-arrays which are of length k.Examples: Input : arr[]={1, 2, 3, 4}, k=2 Output :Sum= 11 Sum = 1^2 + 2^3 + 3^4 = 3 + 1 + 7 =11Input :arr[]={1, 2, 3, 4}, k=3 Output :Sum= 5 Sum = 1^2^3 + 2^3^4 = 0 + 5
    8 min read
  • Count of odd and even sum pairs in an array
    Given an array arr[] of N positive integers, the task is to find the number of pairs with odd sum and the number of pairs with even sum.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: Odd pairs = 6 Even pairs = 4Input: arr[] = {7, 4, 3, 2} Output: Odd pairs = 4 Even pairs = 2 Naive Approach: The na
    8 min read
  • Find sum of XNOR of all unordered pairs from given Array
    Given an array arr[] of size N, the task is to find the sum of all XNOR values of all possible unordered pairs from the given array. Examples: Input: N = 5, arr[] = {2, 2, 2, 1, 1}Output:10Explanation: Here, 2 XNOR 2 = 3, 2 XNOR 2 = 3, 2 XNOR 2 = 3, 1 XNOR 1 = 1, 2 XNOR 1 = 0, 2 XNOR 1 = 0, 2 XNOR 1
    15+ min read
  • Sum of Bitwise AND of all pairs possible from two arrays
    Given two arrays A[] and B[] of size N and M respectively, the task is to find the sum of Bitwise AND of all possible unordered pairs (A[i], B[j]) from the two arrays. Examples: Input: A[] = {1, 2} , B[] = {3, 4} Output: 3 Explanation: Bitwise AND of all possible pairs are 1 & 3 = 1 1 & 4 =
    5 min read
  • Sum of product of all pairs of a Binary Array
    Given a binary array arr[] of size N, the task is to print the sum of product of all pairs of the given array elements. Note: The binary array contains only 0 and 1. Examples: Input: arr[] = {0, 1, 1, 0, 1}Output: 3Explanation: Sum of product of all possible pairs are: {0 × 1 + 0 × 1 + 0 × 0 + 0 × 1
    5 min read
  • Maximum and minimum sum of Bitwise XOR of pairs from an array
    Given an array arr[] of size N, the task is to find the maximum and minimum sum of Bitwise XOR of all pairs from an array by splitting the array into N / 2 pairs. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6 10Explanation:Bitwise XOR of the all possible pair splits are as follows:(1, 2), (3, 4) →
    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
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