Prime XOR


Problem Statement :


Penny has an array of n integers, [a0,a1, a2, ...., an-1]. She wants to find the number of unique multisets she can form using elements from the array such that the bitwise XOR of all the elements of the multiset is a prime number. Recall that a multiset is a set which can contain duplicate elements.

Given q queries where each query consists of an array of integers, can you help Penny find and print the number of valid multisets for each array? As these values can be quite large, modulo each answer by  10^9 + 7 before printing it on a new line.

Input Format

The first line contains a single integer, q, denoting the number of queries. The 2.q subsequent lines describe each query in the following format:

1.The first line contains a single integer, n, denoting the number of integers in the array.
2.The second line contains n space-separated integers describing the respective values of a0, a1,...,an-1.
Constraints

1 <= q <= 10
1 <= n <= 100000
3500 <= ai <= 4500
Output Format

On a new line for each query, print a single integer denoting the number of unique multisets Penny can construct using numbers from the array such that the bitwise XOR of all the multiset's elements is prime. As this value is quite large, your answer must be modulo 10^9 + 7.



Solution :



title-img


                            Solution in C :

In C++ :






#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
typedef long long ll;
ll n,i,j,k,m,x;
ll primes[200005], b[200005], dp[2005][8505];
set<ll> f;
set<ll>::iterator itr;
int main()
{
 //freopen("input.txt","r",stdin);
 for (i = 2; i <= 10000; i++)
  primes[i] = 1;
 for (i = 2; i <= 10000; i++)
  if (primes[i])
  for (j = i*2; j <= 10000; j+=i)
   primes[j] = 0;
 ll q;
 cin >> q;
 while (q--)
 {
  cin >> n;
  for (i = 3500; i <= 4500; i++)
   b[i] = 0;
  for (i = 0; i < n; i++)
  {
   scanf("%lld",&x);
   b[x]++;
  }
  for (i = 0; i <= 1001; i++)
   for (j = 0; j <= 8192; j++)
    dp[i][j] = 0;
  dp[0][0] = 1;
  for (i = 0; i <= 1000; i++)
   for (j = 0; j < 8192; j++)
   {
    dp[i+1][j^(i+3500)] = (dp[i+1][j^(i+3500)] + dp[i][j]*((b[i+3500]+1)/2))%MOD;
    dp[i+1][j] = (dp[i+1][j] + dp[i][j]*(b[i+3500]/2+1))%MOD;
   }
  ll ans = 0;
  for (j = 0; j < 8192; j++)
   if (primes[j])
      ans += dp[1001][j];
  cout << ans%MOD << endl;
 }
 return 0;
}








In Java :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static int mod = 1000000007;
    public static boolean[] prime = new boolean[ 10000 ];
    public static long[] dp = new long[ 1 << 13 ];
    public static long[] dpp = new long[ 1 << 13 ];
    public static long[] val = new long[ 5000 ];
    public static ArrayList< Integer > list = new ArrayList< Integer >();;
    public static void makeArray()
    {
        for( int i = 0; i < 10000; i++ )
            prime[ i ] = true;
        prime[ 0 ] = prime[ 1 ] = false;
        for( int i = 2; i < 10000; i++ )
        {
           if( !prime[ i ] )
            continue;
            for( int j = 2 * i; j < 10000; j += i)
                prime[ j ] = false; 
        }   
    }
    
    public static void check()
    {
        for( int i = 0; i < ( 1 << 13 ); i++ )
        {
            dp[ i ] = dpp[ i ] = 0;
            if( i < 4999 )
                val[ i ] = 0;
        }
        list.clear();
    }
    public static void main(String[] args) {
       
        Scanner input = new Scanner( System.in );
        makeArray();
        int q = input.nextInt();
        while( q > 0 )
        {
            check();
            int n = input.nextInt();
            long ans = 0l;
            for( int i = 0;  i < n; i++ )
            {
                int x = input.nextInt();
                if( val[ x ] == 0 )
                    list.add( x );
                val[ x ]++;
            }
            
            n = list.size();
            
            for( int i = 0; i < n; i++ )
            {
                for( int j = 0; j < ( 1 << 13 ); j++ )
                {
                    long free = val[ list.get( i ) ];
                    long odd = free / 2;
                    
                    odd = ( free % 2 == 0 ) ? odd : odd + 1;
                    long even = 1 + free / 2;
                    
                    if( i != 0 )
                        dp[ j ] = dpp[ j ] * even + dpp[ j ^ list.get( i ) ] * odd;
                    else
                    {
                        dp[ list.get( i ) ] = odd;
                        dp[ 0 ] = even;
                        break;
                    }
                    if( dp[ j ] >= mod )
                        dp[ j ] %= mod;
                }
                
                for( int j = 0; j < ( 1 << 13 ); j++ )
                {
                    if( ( i == n - 1 ) && prime[ j ] )
                    {
                        ans += dp[ j ];
                        if( ans >= mod )
                            ans %= mod;
                    }
                    dpp[ j ] = dp[ j ];
                    dp[ j ] = 0;
                }
            }
            System.out.println( ans );
            q--;
        }
    }
}








In C :






#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOD 1000000007
void gen_primes(int max,int*primes);
int a[1001],p[8192];
long long dp[1002][8192];

int main(){
  int q,n,x,i,j;
  long long ans;
  gen_primes(8191,p);
  scanf("%d",&q);
  while(q--){
    memset(a,0,sizeof(a));
    scanf("%d",&n);
    for(i=0;i<n;i++){
      scanf("%d",&x);
      a[x-3500]++;
    }
    for(i=0;i<8192;i++)
      dp[0][i]=0;
    dp[0][0]=1;
    for(i=0;i<1001;i++){
      for(j=0;j<8192;j++)
        dp[i+1][j]=dp[i][j];
      if(a[i])
        for(j=0;j<8192;j++){
          dp[i+1][j^(i+3500)]=(dp[i+1][j^(i+3500)]+dp[i][j]*((a[i]+1)/2))%MOD;
          dp[i+1][j]=(dp[i+1][j]+dp[i][j]*(a[i]/2))%MOD;
        }
    }
    for(i=ans=0;i<8192;i++)
      if(p[i])
        ans=(ans+dp[1001][i])%MOD;
    printf("%lld\n",ans);
  }
  return 0;
}
void gen_primes(int max,int*primes){
  int i,j;
  for(i=0;i<=max;++i)
    primes[i]=1;
  primes[0]=primes[1]=0;
  for(i=2;i*i<=max;++i){
    if(!primes[i])
      continue;
    for(j=2;i*j<=max;++j)
      primes[i*j]=0;
  }
}








In Python3 :






import math
import os
import random
import re
import sys
import itertools
from itertools import combinations
from collections import Counter

def isPrime(x):
    if x == 1:
        return False
    
    if x == 2:
        return True
    
    for d in range(2, max(2, int(x**0.5)) + 1):
        if x%d == 0:
            return False
    return True


def primeXor(a):
    
    count=0
    c=Counter(a)
    dp=[0]*8192
    dp[0]=1
    cache=[]
    for e in c.keys():
        even=c[e]//2+1
        odd=(c[e]+1)//2
        dp=[(dp[i]*even +dp[i^e]*odd)%(10**9+7) for i in range(8192)]

    for j in range(8192):
        if isPrime(j):
            count+=dp[j]
            if count>(10**9+7):
                count=count%(10**9+7)

    return count

        

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(input())

    for q_itr in range(q):
        n = int(input())

        a = list(map(int, input().rstrip().split()))

        result = primeXor(a)

        fptr.write(str(result) + '\n')

    fptr.close()
                        








View More Similar Problems

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →