Skip to content
Related Articles

Related Articles

Construct a sorted Array such that setbit in bitwise XOR of any pair is even

Improve Article
Save Article
  • Last Updated : 07 Nov, 2022
Improve Article
Save Article

Given an integer N(1 ≤ N ≤ 500), Construct an integer arr[] of length N, such that it should follow all the given conditions below: 

  • Each element of arr[] should be distinct.
  • Binary representation of (arr[i]^arr[j]) should contain even number of set bits for all ( 1≤i≤N ) and ( i≠j ).
  • All the elements in arr[] should be in sorted order.
  • Ai > 0 for all (1 ≤ i ≤ N).

Examples:

Input: N = 2
Output: {10, 15}
Explanation: It can be verified that all elements of arr[] 
in each output are distinct and in sorted order and 
all the possible pairs of arr[] fulfill the condition mentioned in problem statement..

Input: N = 3
Output: {3, 5, 12}

Approach: To solve the problem follow the below observation:

It can be observe from outputs that arr[] contains only elements having even parity of set bits in their binary representation. If we try to get some such type of elements under range 1 to 10 using a brute-force code we will get a mathematical series as { 3, 5, 6, 9}. 

This series is called Evil Number series and related to Number theory. This series follows all the given conditions of the problem. Therefore, This problem can be solve by printing first N terms of Evil Number series(Excluding 0, As Arr[i] should be greater than zero).

Follow the steps to solve the problem:

  • Print the first N terms of Evil number Series or First N integers greater than zero having even parity of set bits.

Below is the implementation for the above approach:

C++




// c++ implementation
#include <bits/stdc++.h>
using namespace std;
string toBinary(int n)
{
  string r;
  while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
  return r;
}
 
// Function which takes binary
// representation of a number
// as String argument and returns
// total number of set bits
int count1(string str)
{
 
  // Counter variable to store
  // number of set bits in
  // binary representation
  int counter = 0;
 
  // Loop for traversing on
  // Binary String
  for (int i = 0; i < str.size(); i++)
  {
 
    // Condition when character
    // '1' found in string
    if (str[i] == '1')
    {
 
      // Incrementing counter
      counter++;
    }
  }
 
  // Returning count of set bits
  return counter;
}
 
int main() {
  // Input value of N
  int N = 10;
 
  // Counter variable
  int counter = 1;
 
  // Loop for finding first N terms
  // of Evil Numbers Series
  for (int i = 1; i <= N; i++) {
 
    // While Loop which executes
    // till counter is not a member
    // of Evil Number series
 
    while ((count1(toBinary(counter)))
           % 2
           != 0) {
 
      // Incrementing counter
      counter++;
    }
 
    // Printing current value
    // of counter
    cout<<counter<<" ";
 
    // Incrementing counter
    counter++;
 
  } //for loop end
  return 0;
}
 
// this code is contributed by ksam24000


Java




// Java code to implement the approach
 
// Brute force solution to find first N
// terms such that all the terms have even
// parity of set bits in their binary
// representation
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
        throws java.lang.Exception
    {
        // Input value of N
        int N = 10;
 
        // Counter variable
        int counter = 1;
 
        // Loop for finding first N terms
        // of Evil Numbers Series
        for (int i = 1; i <= N; i++) {
 
            // While Loop which executes
            // till counter is not a member
            // of Evil Number series
            while ((count1(Integer.toBinaryString(counter)))
                       % 2
                   != 0) {
 
                // Incrementing counter
                counter++;
            }
 
            // Printing current value
            // of counter
            System.out.print(counter + " ");
 
            // Incrementing counter
            counter++;
        }
    }
 
    // Function which takes binary
    // representation of a number
    // as String argument and returns
    // total number of set bits
    static int count1(String str)
    {
 
        // Counter variable to store
        // number of set bits in
        // binary representation
        int counter = 0;
 
        // Loop for traversing on
        // Binary String
        for (int i = 0; i < str.length(); i++) {
 
            // Condition when character
            // '1' found in string
            if (str.charAt(i) == '1')
 
                // Incrementing counter
                counter++;
        }
 
        // Returning count of set bits
        return counter;
    }
}


Python3




class GFG :
    # Driver code
    @staticmethod
    def main( args) :
       
        # Input value of N
        N = 10
         
        # Counter variable
        counter = 1
         
        # Loop for finding first N terms
        # of Evil Numbers Series
        i = 1
        while (i <= N) :
           
            # While Loop which executes
            # till counter is not a member
            # of Evil Number series
            while ((GFG.count1(str(bin(counter)))) % 2 != 0) :
               
                # Incrementing counter
                counter += 1
                 
            # Printing current value
            # of counter
            print(str(counter) + " ", end ="")
             
            # Incrementing counter
            counter += 1
            i += 1
             
    # Function which takes binary
    # representation of a number
    # as String argument and returns
    # total number of set bits
    @staticmethod
    def  count1( str) :
       
        # Counter variable to store
        # number of set bits in
        # binary representation
        counter = 0
         
        # Loop for traversing on
        # Binary String
        i = 0
        while (i < len(str)) :
           
            # Condition when character
            # '1' found in string
            if (str[i] == '1') :
               
                # Incrementing counter
                counter += 1
            i += 1
             
        # Returning count of set bits
        return counter
     
 
if __name__=="__main__":
    GFG.main([])
     
    # This code is contributed by aadityaburujwale.


C#




// Include namespace system
using System;
 
public class GFG
{
 
  // Driver code
  public static void Main(String[] args)
  {
 
    // Input value of N
    var N = 10;
 
    // Counter variable
    var counter = 1;
 
    // Loop for finding first N terms
    // of Evil Numbers Series
    for (int i = 1; i <= N; i++)
    {
 
      // While Loop which executes
      // till counter is not a member
      // of Evil Number series
      while ((GFG.count1(Convert.ToString(counter, 2))) % 2 != 0)
      {
 
        // Incrementing counter
        counter++;
      }
         
      // Printing current value
      // of counter
      Console.Write(counter.ToString() + " ");
 
      // Incrementing counter
      counter++;
    }
  }
 
  // Function which takes binary
  // representation of a number
  // as String argument and returns
  // total number of set bits
  public static int count1(String str)
  {
 
    // Counter variable to store
    // number of set bits in
    // binary representation
    var counter = 0;
 
    // Loop for traversing on
    // Binary String
    for (int i = 0; i < str.Length; i++)
    {
 
      // Condition when character
      // '1' found in string
      if (str[i] == '1')
      {
 
        // Incrementing counter
        counter++;
      }
    }
 
    // Returning count of set bits
    return counter;
  }
}
 
// This code is contributed by aadityaburujwale.


Javascript




// js implementation
function toBinary(n)
{
  let r = "";
  while(n != 0) {r = (n % 2 == 0 ? "0":"1") + r; n = Math.floor(n/2);}
  return r;
}
 
// Function which takes binary
// representation of a number
// as String argument and returns
// total number of set bits
function count1(str)
{
 
  // Counter variable to store
  // number of set bits in
  // binary representation
  let counter = 0;
 
  // Loop for traversing on
  // Binary String
  for (let i = 0; i < str.length; i++)
  {
 
    // Condition when character
    // '1' found in string
    if (str[i] == '1')
    {
 
      // Incrementing counter
      counter++;
    }
  }
 
  // Returning count of set bits
  return counter;
}
 
// driver code
  // Input value of N
  let N = 10;
 
  // Counter variable
  let counter = 1;
 
  // Loop for finding first N terms
  // of Evil Numbers Series
  for (let i = 1; i <= N; i++) {
 
    // While Loop which executes
    // till counter is not a member
    // of Evil Number series
 
        while ((count1(toBinary(counter)))
           % 2
           != 0) {
 
      // Incrementing counter
      counter++;
        }
 
    // Printing current value
    // of counter
    console.log(counter);
     
    // Incrementing counter
    counter++;
    }
     
// This code is contributed by ksam24000


Output

3 5 6 9 10 12 15 17 18 20 

Time Complexity: O(N2)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!