Wednesday 2 August 2017

Xor-sequence (a very good question on 1 to n ........in constant time O(1) approach

An array, , is defined as follows:

  • for , where is the symbol for XOR
You must answer questions. Each question, is in the form , and the answer is (the Xor-Sum of segment ).
Print the answer to each question.
Input Format
The first line contains (the number of questions).
The subsequent lines each contain two space separated integers, and , respectively. Line contains and .
Constraints


Subtasks
For score:
Output Format
On a new line for each test case , print the exclusive-or of 's elements in the inclusive range between indices and .
Sample Input
3
2 4
2 8
5 9
Sample Output
7
9
15
Explanation
The beginning of our array looks like this:
Test Case 0:

Test Case 1:

Test Case 2:


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
long actual_number(long m)
{
    if (m%4==0)
        return m;
    if (m%4==1)
        return 1;
    if ((m%4)==2)
        return m+1;
    if (m%4==3)
        return 0;
    return 0;
}
int main(){
    int Q;
    scanf("%d",&Q);
    for(int a0 = 0; a0 < Q; a0++){
        long L;
        long R;
        scanf("%ld %ld",&L,&R);
        long final=0 ;
        long final1=0 ,final2=0;
       while (L%4!=0 && L<R)
        { final1= (final1 ^ actual_number (L)) ;
          // printf("%d  ",actual_number);
            L++;
        }
        if (L==R )
        {
            printf("%ld\n",final1^actual_number(L));
            continue;
        }
           while (R%4!=3 && L<R)
        {
            final2 = (final2^actual_number(R));
            //  printf("%d   ",actual_number(R));
            R--;
        }
        if (L==R)
        {
            printf("%ld\n",(final2^final1^actual_number(R)));
            continue;
        }
       // printf("\nL is %ld and R is %ld",L,R);
       // printf("\n final1 is %d and final 2 is %d",final1,final2);
        if (((R-L+1)%8)==0  )
        {
            final = final1^final2;
        }
        else          // it will definetlty be 3
        {
            final = (final1 ^ final2 ^ 2);
          
        }
       
         printf("%ld\n",final);
    }
   
    return 0;
}



No comments:

Post a Comment