Generate an array of minimum sum whose XOR of same-indexed elements with given array are Prime Numbers
Last Updated :
15 Apr, 2021
Given an array Arr[] of N ( 1 ? N ? 105)integers, the task is to generate an array B[] consisting of N non-zero elements, such that XOR of Ai ^ Bi always results in a prime number.
Note: The sum of XORs obtained should be minimized.
Examples:
Input: arr[] = {5, 4, 7, 6}
Output: {7, 6, 5, 4}
Explanation:
2 is the smallest prime number. Therefore, XORing A[i] with (A[i] ^ 2)
gives us the smallest number which is prime.
A[i] ^ (A[i] ^ 2) = (A[i] ^ A[i]) ^ 2 = 0 ^ 2 = 2
because
1. XOR of 5 ^ 7 = 2, which is prime
2. XOR of 4 ^ 6 = 2, which is prime.
3. XOR of 7 ^ 5 = 2, which is prime.
4. XOR of 6 ^ 4 = 2, which is prime.
The resultant sum is – 2 + 2 + 2 + 2 = 8, which is the minimum possible
Input: arr[] = {10, 16}
Output: {8, 18}
Approach: This problem can be solved using a Greedy technique. Follow the steps below to solve the problem:
- Since 2 is the smallest prime number possible, XOR of Arr[i] with B[i] = (Arr[i] ^ 2) will give us a prime number 2.
- The contradiction arises when any of the array elements itself is Arr[i] = 2. In this case, B[i] = 2 ^ 2 results in 0.
- Therefore, if Arr[i] = 2, set B[i] = (2 ^ 3) = 1, such that Arr[i] ^ K = 3, next smallest prime number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minXOR(vector< int >& Arr, int N)
{
for ( int i = 0; i < N; i++) {
if (Arr[i] == 2) {
cout << (Arr[i] ^ 3) << " " ;
}
else {
cout << (Arr[i] ^ 2) << " " ;
}
}
}
int main()
{
vector< int > Arr = { 5, 4, 7, 6 };
int N = Arr.size();
minXOR(Arr, N);
return 0;
}
|
Java
class GFG{
private static void minXOR( int Arr[], int N)
{
for ( int i = 0 ; i < N; i++)
{
if (Arr[i] == 2 )
{
System.out.print((Arr[i] ^ 3 ) + " " );
}
else
{
System.out.print((Arr[i] ^ 2 ) + " " );
}
}
}
public static void main(String[] args)
{
int Arr[] = { 5 , 4 , 7 , 6 };
int N = Arr.length;
minXOR(Arr, N);
}
}
|
Python3
def minXOR(Arr, N):
for i in range (N):
if (Arr[i] = = 2 ):
print (Arr[i] ^ 3 ,end = " " )
else :
print (Arr[i] ^ 2 ,end = " " )
if __name__ = = '__main__' :
Arr = [ 5 , 4 , 7 , 6 ]
N = len (Arr)
minXOR(Arr, N)
|
C#
using System;
class GFG{
private static void minXOR( int [] Arr, int N)
{
for ( int i = 0; i < N; i++)
{
if (Arr[i] == 2)
{
Console.Write((Arr[i] ^ 3) + " " );
}
else
{
Console.Write((Arr[i] ^ 2) + " " );
}
}
}
public static void Main()
{
int [] Arr = { 5, 4, 7, 6 };
int N = Arr.Length;
minXOR(Arr, N);
}
}
|
Javascript
<script>
function minXOR(Arr, N)
{
for (let i = 0; i < N; i++)
{
if (Arr[i] == 2)
{
document.write((Arr[i] ^ 3) + " " );
}
else
{
document.write((Arr[i] ^ 2) + " " );
}
}
}
let Arr = [ 5, 4, 7, 6 ];
let N = Arr.length;
minXOR(Arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...