Sum of all composite numbers lying in the range [ L , R ] for Q queries | Prefix array to precompute the sum of all composite numbers ; Function that return number num if num is composite else return 0 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to precompute the sum of all Composite numbers upto 10 ^ 5 ; isComposite ( ) return the number i if i is Composite else return 0 ; Function to print the sum for each query ; Function to print sum of all Composite numbers between [ L , R ] ; Function that pre computes the sum of all Composite numbers ; Iterate over all Queries to print the sum ; Queries ; Function that print the the sum of all composite number in Range [ L , R ]
var pref = Array ( 100001 ) . fill ( 0 ) ; function isComposite ( n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 0 ; if ( n % 2 == 0 n % 3 == 0 ) return n ; for ( var i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return n ; return 0 ; } function preCompute ( ) { for ( var i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isComposite ( i ) ; } } function printSum ( L , R ) { document . write ( pref [ R ] - pref [ L - 1 ] + " " ) ; } function printSumComposite ( arr , Q ) { preCompute ( ) ; for ( var i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } var Q = 2 ; var arr = [ [ 10 , 13 ] , [ 12 , 21 ] ] ; printSumComposite ( arr , Q ) ;