Bitwise XOR of first N natural numbers that are product of two distinct Prime Numbers - GeeksforGeeks

29 Jun, 2021
Given a positive integer N, the task is to calculate the Bitwise XOR of first N numbers which are a product of exactly two distinct prime numbers.
Examples:
Input: N = 20Output: 7Explanation: The numbers from the range [1, 20] which are a product of exactly two distinct prime numbers are {6, 10, 12, 14, 15, 18, 20}.Bitwise XOR of these numbers = 6 ^ 10 ^ 12 ^ 14 ^ 15 ^ 18 ^ 20 = 7
Input: N = 50Output: 26
Naive Approach: The simplest approach is to iterate over each number up to N and find the prime factors of each number using the prime factorization method. The numbers for which the count of distinct prime factors are found to be two, then calculate their XOR with the answer. After checking all the numbers, print the answer obtained. 
Time Complexity: O(N*√N)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use the Sieve of Eratosthenes with a little modification. Follow the steps below to solve the problem:
Initialize a variable ans as 0 to store the required result.
Create an integer array, arr[] of size N+1, and initialize with all zeros, where arr[i] denotes the number of distinct prime numbers of i.
Iterate in the range [2, N] using the variable i and if the value of arr[i] is 0 then, go through all the multiples of i using the variable j and increment arr[j] value by 1 since i is a prime factor of j.
Iterate in the range [2, N] using the variable i and if arr[i] is equal to 2, then take XOR of i with ans.
Print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count prime factors// using Sieve of Eratosthenesvoid sieve(int arr[], int n){    // Iterate in the [2, N]    for (int i = 2; i <= n; i++) {         // If the current number is prime        if (arr[i] == 0)             // Iterate over all multiples of i            for (int j = 2 * i; j <= n; j += i) {                 // Increment arr[j] by 1 since                // i is a prime factor of j                arr[j]++;            }    }} // Function to find Bitwise XOR// of first N natural numbers// satisfying the given conditionvoid findXOR(int n){    // arr[i]: Stores the number of    // distinct prime factors of i    int arr[n + 1] = { 0 };     // Initialize the base cases    arr[0] = arr[1] = 1;     // Function Call to fill    // the array, arr[]    sieve(arr, n);     // Store the required result    int ans = 0;     // Iterate over the range [2, N]    for (int i = 2; i <= n; i++) {         // Check if the i-th number has        // exactly two distinct prime factor        if (arr[i] == 2) {             // If true, update the answer            ans = (ans ^ i);        }    }     // Print the result    cout << ans;} // Driver Codeint main(){    // Given Input    int n = 20;     // Function Call    findXOR(n);     return 0;}
// Java program for the above approachpublic class GFG {     // Function to count prime factors    // using Sieve of Eratosthenes    static void sieve(int arr[], int n)    {        // Iterate in the [2, N]        for (int i = 2; i <= n; i++) {             // If the current number is prime            if (arr[i] == 0)                 // Iterate over all multiples of i                for (int j = 2 * i; j <= n; j += i) {                     // Increment arr[j] by 1 since                    // i is a prime factor of j                    arr[j]++;                }        }    }     // Function to find Bitwise XOR    // of first N natural numbers    // satisfying the given condition    static void findXOR(int n)    {               // arr[i]: Stores the number of        // distinct prime factors of i        int arr[] = new int[n + 1];         // Initialize the base cases        arr[0] = arr[1] = 1;         // Function Call to fill        // the array, arr[]        sieve(arr, n);         // Store the required result        int ans = 0;         // Iterate over the range [2, N]        for (int i = 2; i <= n; i++) {             // Check if the i-th number has            // exactly two distinct prime factor            if (arr[i] == 2) {                 // If true, update the answer                ans = (ans ^ i);            }        }         // Print the result        System.out.println(ans);    }     // Driver code    public static void main(String[] args)    {      // Given Input        int n = 20;         // Function Call        findXOR(n);    }} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to count prime factors# using Sieve of Eratosthenesdef sieve(arr, n):         # Iterate in the [2, N]    for i in range(2, n + 1, 1):                 # If the current number is prime        if (arr[i] == 0):                         # Iterate over all multiples of i            for j in range(2 * i, n + 1, i):                                 # Increment arr[j] by 1 since                # i is a prime factor of j                arr[j] += 1 # Function to find Bitwise XOR# of first N natural numbers# satisfying the given conditiondef findXOR(n):         # arr[i]: Stores the number of    # distinct prime factors of i    arr = [0 for i in range(n + 1)]     # Initialize the base cases    arr[0] = arr[1] = 1     # Function Call to fill    # the array, arr[]    sieve(arr, n)     # Store the required result    ans = 0     # Iterate over the range [2, N]    for i in range(2, n + 1, 1):                 # Check if the i-th number has        # exactly two distinct prime factor        if (arr[i] == 2):                         # If true, update the answer            ans = (ans ^ i)     # Print the result    print(ans) # Driver Codeif __name__ == '__main__':         # Given Input    n = 20         # Function Call    findXOR(n)         # This code is contributed by SURENDRA_GANGWAR
// C# program for the above approachusing System; class GFG{ // Function to count prime factors// using Sieve of Eratosthenesstatic void sieve(int []arr, int n){         // Iterate in the [2, N]    for(int i = 2; i <= n; i++)    {                 // If the current number is prime        if (arr[i] == 0)             // Iterate over all multiples of i            for(int j = 2 * i; j <= n; j += i)            {                                 // Increment arr[j] by 1 since                // i is a prime factor of j                arr[j]++;            }    }} // Function to find Bitwise XOR// of first N natural numbers// satisfying the given conditionstatic void findXOR(int n){         // arr[i]: Stores the number of    // distinct prime factors of i    int []arr = new int[n + 1];     // Initialize the base cases    arr[0] = arr[1] = 1;     // Function Call to fill    // the array, arr[]    sieve(arr, n);     // Store the required result    int ans = 0;     // Iterate over the range [2, N]    for(int i = 2; i <= n; i++)    {                 // Check if the i-th number has        // exactly two distinct prime factor        if (arr[i] == 2)        {             // If true, update the answer            ans = (ans ^ i);        }    }     // Print the result    Console.WriteLine(ans);} // Driver codepublic static void Main(String[] args){         // Given Input    int n = 20;         // Function Call    findXOR(n);}} // This code is contributed by ankThon
<script> // JavaScript program for the above approach // Function to count prime factors// using Sieve of Eratosthenesfunction  sieve( arr, n){    // Iterate in the [2, N]    for (var i = 2; i <= n; i++) {         // If the current number is prime        if (arr[i] == 0)             // Iterate over all multiples of i            for (var j = 2 * i; j <= n; j += i) {                 // Increment arr[j] by 1 since                // i is a prime factor of j                arr[j]++;            }    }} // Function to find Bitwise XOR// of first N natural numbers// satisfying the given conditionfunction findXOR( n){    // arr[i]: Stores the number of    // distinct prime factors of i    var arr = new Array(n + 1);    arr.fill(0);     // Initialize the base cases    arr[0] = arr[1] = 1;     // Function Call to fill    // the array, arr[]    sieve(arr, n);     // Store the required result    var ans = 0;     // Iterate over the range [2, N]    for (var i = 2; i <= n; i++) {         // Check if the i-th number has        // exactly two distinct prime factor        if (arr[i] == 2) {             // If true, update the answer            ans = (ans ^ i);        }    }     // Print the result    document.write( ans);} n = 20; // Function CallfindXOR(n); // This code is contributed by SoumikMondal </script>
7
 
Time Complexity: O(N*log(logN))Auxiliary Space: O(N)
 
abhinavjain194
SURENDRA_GANGWAR
ankthon
SoumikMondal
Natural Numbers
Prime Number
sieve
Arrays
Mathematical
Arrays
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7