Find Multiples of 2 or 3 or 5 less than or equal to N | CPP program to count number of multiples of 2 or 3 or 5 less than or equal to N ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMultiples ( int n ) { int multiple [ ] = { 2 , 3 , 5 } ; int count = 0 , mask = pow ( 2 , 3 ) ; for ( int i = 1 ; i < mask ; i ++ ) { int prod = 1 ; for ( int j = 0 ; j < 3 ; j ++ ) { if ( i & 1 << j ) prod = prod * multiple [ j ] ; } if ( __builtin_popcount ( i ) % 2 == 1 ) count = count + n / prod ; else count = count - n / prod ; } return count ; } int main ( ) { int n = 10 ; cout << countMultiples ( n ) << endl ; return 0 ; }