// C# implementation of the approach
using System;
class GFG
{
static int bitscount = 32 ;
static int n = 3 ;
// Array to store bit-wise
// prefix count
static int [,,]prefix_count = new int [bitscount,n,n];
// Function to find the prefix sum
static void findPrefixCount(int [,]arr)
{
// Loop for each bit
for (int i = 0; i < bitscount; i++)
{
// Loop to find prefix-count
// for each row
for (int j = 0; j < n; j++)
{
prefix_count[i,j,0] = ((arr[j,0] >> i) & 1);
for (int k = 1; k < n; k++)
{
prefix_count[i, j, k] = ((arr[j,k] >> i) & 1);
prefix_count[i, j, k] += prefix_count[i, j, k - 1];
}
}
}
// Finding column-wise prefix
// count
for (int i = 0; i < bitscount; i++)
for (int j = 1; j < n; j++)
for (int k = 0; k < n; k++)
prefix_count[i, j, k] += prefix_count[i, j - 1, k];
}
// Function to return the result for a query
static int rangeAnd(int x1, int y1, int x2, int y2)
{
// To store the answer
int ans = 0;
// Loop for each bit
for (int i = 0; i < bitscount; i++)
{
// To store the number of variables
// with ith bit set
int p;
if (x1 == 0 && y1 == 0)
p = prefix_count[i, x2, y2];
else if (x1 == 0)
p = prefix_count[i, x2, y2]
- prefix_count[i, x2, y1 - 1];
else if (y1 == 0)
p = prefix_count[i, x2, y2]
- prefix_count[i, x1 - 1, y2];
else
p = prefix_count[i, x2, y2]
- prefix_count[i, x1 - 1, y2]
- prefix_count[i, x2, y1 - 1]
+ prefix_count[i, x1 - 1, y1 - 1];
// If count of variables whose ith bit
// is set equals to the total
// elements in the sub-matrix
if (p == (x2 - x1 + 1) * (y2 - y1 + 1))
ans = (ans | (1 << i));
}
return ans;
}
// Driver code
public static void Main (String[] args)
{
int [,]arr = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
findPrefixCount(arr);
int [,]queries = { { 1, 1, 1, 1 }, { 1, 2, 2, 2 } };
int q = queries.GetLength(0);
for (int i = 0; i < q; i++)
Console.WriteLine( rangeAnd(queries[i,0],
queries[i,1],
queries[i,2],
queries[i,3]) );
}
}
/* This code contributed by PrinciRaj1992 */