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

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →