Find the XOR of first N Prime Numbers | Javascript implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to return the xor of 1 st N prime numbers ; Count of prime numbers ; XOR of prime numbers ; If the number is prime xor it ; Increment the count ; Get to the next number ; Create the sieve ; Find the xor of 1 st n prime numbers
let MAX = 10000 ; let prime = new Array ( MAX + 1 ) ; function SieveOfEratosthenes ( ) { let i ; for ( i = 0 ; i < MAX + 1 ; i ++ ) { prime [ i ] = true ; } prime [ 1 ] = false ; for ( let p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } function xorFirstNPrime ( n ) { let count = 0 , num = 1 ; let xorVal = 0 ; while ( count < n ) { if ( prime [ num ] ) { xorVal ^= num ; count ++ ; } num ++ ; } return xorVal ; } SieveOfEratosthenes ( ) ; let n = 4 ; document . write ( xorFirstNPrime ( n ) ) ;