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, with sum1 we will perform bitwise OR operation for each jth element, and add sum1 with sum.
- Traverse the from 0th position to n-1.
- For each ith variable we will perform bit wise OR operation on all the sub arrays to find the total sum.
Repeat step until the whole array is traverse.
C++
#include <iostream>
using namespace std;
int totalSum( int a[], int n)
{
int i, sum = 0, sum1 = 0, j;
for (i = 0; i < n; i++)
{
sum1 = 0;
for (j = i; j < n; j++)
{
sum1 = (sum1 | a[j]);
sum = sum + sum1;
}
}
return sum;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof (a) / sizeof (a[0]);
cout << totalSum(a, n) << endl;
return 0;
}
|
C
#include <stdio.h>
int totalSum( int a[], int n)
{
int i, sum = 0, sum1 = 0, j;
for (i = 0; i < n; i++) {
sum1 = 0;
for (j = i; j < n; j++) {
sum1 = (sum1 | a[j]);
sum = sum + sum1;
}
}
return sum;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof (a)/ sizeof (a[0]);
printf ( "%d " , totalSum(a, n));
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int totalSum( int a[], int n)
{
int i, sum = 0 , sum1 = 0 , j;
for (i = 0 ; i < n; i++)
{
sum1 = 0 ;
for (j = i; j < n; j++)
{
sum1 = (sum1 | a[j]);
sum = sum + sum1;
}
}
return sum;
}
public static void main(String args[])
{
int a[] = { 1 , 2 , 3 , 4 , 5 };
int n = a.length;
System.out.println(totalSum(a,n));
}
}
|
Python3
def totalSum(a, n):
sum = 0 ;
for i in range (n):
sum1 = 0 ;
for j in range (i, n):
sum1 = (sum1 | a[j]);
sum = sum + sum1;
return sum ;
a = [ 1 , 2 , 3 , 4 , 5 ];
n = len (a);
print (totalSum(a, n));
|
C#
using System;
class GFG
{
static int totalSum( int [] a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
int sum1 = 0;
for ( int j = i; j < n; j++)
{
sum1 = (sum1 | a[j]);
sum = sum + sum1;
}
}
return sum;
}
static void Main()
{
int [] a = { 1, 2, 3, 4, 5 };
int n = a.Length;
Console.WriteLine(totalSum(a,n));
}
}
|
PHP
<?php
function totalSum( $a , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$sum1 = 0;
for ( $j = $i ; $j < $n ; $j ++)
{
$sum1 = ( $sum1 | $a [ $j ]);
$sum = $sum + $sum1 ;
}
}
return $sum ;
}
$a = array (1, 2, 3, 4, 5);
$n = sizeof( $a );
echo totalSum( $a , $n );
?>
|
Javascript
<script>
function totalSum(a, n)
{
let i, sum = 0, sum1 = 0, j;
for (i = 0; i < n; i++)
{
sum1 = 0;
for (j = i; j < n; j++)
{
sum1 = (sum1 | a[j]);
sum = sum + sum1;
}
}
return sum;
}
let a = [ 1, 2, 3, 4, 5 ];
let n = a.length;
document.write(totalSum(a,n));
</script>
|
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...