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

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →