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

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →