Given an integer . The task is to count all such numbers that are less than or equal to N which are divisible by any of 2 or 3 or 5.
Note: If a number less than N is divisible by both 2 or 3, or 3 or 5, or all of 2,3 and 5 then also it should be counted only once.
Input : N = 5 Output : 4 Input : N = 10 Output : 8
Simple Approach: A simple approach is to traverse from 1 to N and count multiple of 2, 3, 5 which are less than equal to N. To do this, iterate up to N and just check whether a number is divisible by 2 or 3 or 5. If it is divisible, increment the counter and after reaching N, print the result.
Time Complexity: O(N).
Efficient Approach: An efficient approach is to use the concept of set theory. As we have to find numbers that are divisible by 2 or 3 or 5.
Now the task is to find n(a),n(b),n(c),n(ab), n(bc), n(ac), and n(abc). All these terms can be calculated using Bit masking. In this problem we have taken three numbers 2,3, and 5. So, the bit mask should be of 2^3 bits i.e 8 to generate all combination of 2,3, and 5.
Now according to the formula of set union, all terms containing odd numbers of (2,3,5) will add into the result and terms containing even number of (2,3,5) will get subtracted.
Below is the implementation of the above approach:
- Count of Multiples of A ,B or C less than or equal to N
- Find the sum of all multiples of 2 and 5 below N
- Find numbers which are multiples of first array and factors of second array
- Find all factorial numbers less than or equal to n
- Find a Number X whose sum with its digits is equal to N
- Find three integers less than or equal to N such that their LCM is maximum
- Find the first N integers such that the sum of their digits is equal to 10
- Find an N x N grid whose xor of every row and column is equal
- Find a number x such that sum of x and its digits is equal to given n.
- Multiples of 3 or 7
- Sum of all the multiples of 3 and 7 below N
- Sum of multiples of A and B less than N
- Find four factors of N with maximum product and sum equal to N | Set 3
- Find four factors of N with maximum product and sum equal to N
- Find N distinct numbers whose bitwise Or is equal to K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.