Multiples of 3 or 7 in C++

C++Server Side ProgrammingProgramming

Given a number n, we need to find the count of multiples of 3 or 7 till n. Let's see an example.

Input

100

Output

43

There are total of 43 multiples of 3 or 7 till 100.

Algorithm

  • Initialise the number n.

  • Initialise the count to 0.

  • Write a loop that iterates from 3 to n.

    • Increment the count if the current number is divisible by 3 or 7.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getMultiplesCount(int n) {
   int count = 0;
   for (int i = 3; i <= n; i++) {
      if (i % 3 == 0 || i % 7 == 0) {
         count++;
      }
   }
   return count;
}
int main() {
   cout << getMultiplesCount(100) << endl;
}

Output

If you run the above code, then you will get the following result.

43
raja
Published on 01-Jul-2021 06:57:40
Advertisements