Multiples of 3 or 7 - GeeksforGeeks
Given a positive integer n, find count of all multiples of 3 or 7 less than or equal to n.
Read full article from Multiples of 3 or 7 - GeeksforGeeks
Given a positive integer n, find count of all multiples of 3 or 7 less than or equal to n.
An efficient solution can solve the above problem in O(1) time. The idea is to count multiples of 3 and add multiples of 7, then subtract multiples of 21 because these are counted twice.
count = n/3 + n/7 - n/21
int countMultiples(int n){ return n/3 + n/7 -n/21;}int countMultiples(int n){ int res = 0; for (int i=1; i<=n; i++) if (i%3==0 || i%7 == 0) res++; return res;}