Find Multiples of 2 or 3 or 5 less than or equal to N in C++


In this problem, we are given a number N. Our task is to Find Multiples of 2 or 3 or 5 less than or equal to N.

Problem Description − We will be counting all elements from 1 to N that are divisible by 2 or 3 or 5.

Let’s take an example to understand the problem,

Input

N = 7

Output

5

Explanation

All the elements from 1 to 7 are : 1, 2, 3, 4, 5, 6, 7.
Elements divisible by 2/3/5 are 2, 3, 4, 5, 6

Solution Approach

A simple approach to solve the problem is by traversing all numbers from 1 to N and count all numbers that are divided by 2 or 3 or 5.

ALGORITHM

Initialize − count = 0

Step 1 − loop for i = 1 to N.

Step 1.1: if(i%2 == 0 || i%3 == 0 || i%5 == 0), count++.

Step 2 − return count.

Another approach

A more effective approach to solve the problem is using the set theory.

The count of number divisible by 2 is n(2)

The count of number divisible by 3 is n(3)

The count of number divisible by 5 is n(5)

The count of number divisible by 2 and 3 is n(2 n 3)

The count of number divisible by 2 and 5 is n(2 n 5)

The count of number divisible by 3 and 5 is n(3 n 5)

The count of number divisible by 2 and 3 and 5 is n(2 n 3 n 5)

The count of number divisible by 2 or 3 or 5 is n(2 U 3 U 5)

Based on set theory,

n(2 ∪ 3 ∪ 5) = n(2) + n(3) + n(5) - n(2 ∩ 3) - n(2 ∩ 5) - n(3 ∩ 5) + n(2 ∩ 3 ∩ 5)

The solution is found by calculating the bit masks of numbers.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countMultiples(int n) {
   int values[] = { 2, 3, 5 };
   int countMultiples = 0, bitMask = pow(2, 3);
   for (int i = 1; i < bitMask; i++) {
      int prod = 1;
      for (int j = 0; j < 3; j++) {
         if (i & 1 << j)
            prod = prod * values[j];
      }
      if (__builtin_popcount(i) % 2 == 1)
         countMultiples = countMultiples + n / prod;
      else
         countMultiples = countMultiples - n / prod;
   }
   return countMultiples;
}
int main() {
   int n = 13;
   cout<<"The number of multiples till "<<n<<" is "<<countMultiples(n)<<endl;
   return 0;
}

Output

The number of multiples till 13 is 9

Updated on: 12-Mar-2021

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements