- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Count the numbers divisible by â€˜Mâ€™ in a given range in C++

We are given three numbers A,B and M. A and B define the range [A,B] of numbers.The goal is to count numbers between A and B that are divisible by M.

We will start from i=A till first multiple of M. Increment count if i%M=0. Now increment i till i<=B and increase count.

Let’s understand with examples.

## Input

A=11,B=20, M=5

## Output

Count of numbers divisible by M in given range: 2

## Explanation

15 and 20 are only numbers that are divisible by 5 and lie in range [11,20].

## Input

A=20, B=50, M=11

## Output

Count of numbers divisible by M in given range: 3

## Explanation

22,33,44 are only numbers that are divisible by 11 and lie in range [20,50].

## Approach used in the below program is as follows

- We take A,B and M as integers.
- Function divisiblebyM (int a, int b, int m) take A,B and M as parameters and return the count of numbers between A and B that are divisible by M.
- Take the initial count as 0.
- Using for loop, start from i=A to i=B. Increment i by 1.
- If i%m=0, increment count.
- At the end, count as numbers between A and B that are divisible by m.
- Return count as result.

## Example

// Program to count the numbers divisible by // M in a given range #include <bits/stdc++.h> using namespace std; int divisiblebyM(int a, int b, int m){ int count = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = a; i <= b;i++ ){ if (i % m == 0){ count++; } } return count; } int main(){ // A and B define the range, M is the dividend int A = 3, B = 15, M = 4; cout<<"Numbers divisible by M in given range:"<<divisiblebyM(A, B, M) << endl; return 0; }

## Output

Numbers divisible by M in given range:3

Advertisements