-6
#include <stdio.h>
#include <math.h>

int main()
{

     int n,i,j;long long p,sum=0,count;
     scanf("%d",&n);
     long long a[n];


     for(i=0;i<n;i++)
          scanf("%lld",&a[i]);

     for(j=0;j<64;j++)
     {
         count=0;
         p=pow(2,j);

         for(i=0;i<n;i++)
             {
                 **if(a[i]&p)**
                 count++;
             }

         sum+=(count*(count-1)*p/2);
     }

     printf("%lld",sum);
     return 0;
}

what does if statement in second for loop do here? And why & is used in program?

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
yashpatelyk
  • 419
  • 3
  • 11

3 Answers3

1

The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.

For instance, working with a byte (the char type):

EX.

01001000 & 
10111000 = 
--------
00001000

The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left. Consequently,

72 & 184 = 8

More example

   unsigned int a = 60; /* 60 = 0011 1100 */  
   unsigned int b = 13; /* 13 = 0000 1101 */
   int c = 0;           

   c = a & b;       /* 12 = 0000 1100 */ 
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
0

& is the bitwise AND operator. It does what that sounds like - does the and operator on every bit. In your case, if p = 2^k, a[i]&p checks if the machine's binary representation of a[i] has the k-th bit set to 1.

Pradhan
  • 16,391
  • 3
  • 44
  • 59
0

AND operator compares two given inputs bits and makes result as 1 if both bits are 1. Else it gives 0.

rohit
  • 198
  • 1
  • 1
  • 7