Find Multiples of 2 or 3 or 5 less than or equal to N | Bit count function ; Function to count number of multiples of 2 or 3 or 5 less than or equal to N ; As we have to check divisibility by three numbers , So we can implement bit masking ; we check whether jth bit is set or not , if jth bit is set , simply multiply to prod ; check for set bit ; check multiple of product ; Driver code
function count_setbits ( N ) { var cnt = 0 ; while ( N > 0 ) { cnt += ( N & 1 ) ; N = N >> 1 ; } return cnt ; } function countMultiples ( n ) { var multiple = [ 2 , 3 , 5 ] ; var count = 0 , mask = parseInt ( Math . pow ( 2 , 3 ) ) ; for ( i = 1 ; i < mask ; i ++ ) { var prod = 1 ; for ( j = 0 ; j < 3 ; j ++ ) { if ( ( i & 1 << j ) > 0 ) prod = prod * multiple [ j ] ; } if ( count_setbits ( i ) % 2 == 1 ) count = count + parseInt ( n / prod ) ; else count = count - parseInt ( n / prod ) ; } return count ; } var n = 10 ; document . write ( countMultiples ( n ) ) ;