# Count n digit numbers divisible by given number in C++

We are given the two elements let’s say, d and num, the task is to find the d digit numbers which are divisible by num.

In simple words let us suppose we have given an input 2 in d, so we will first find all the 2-digit numbers i.e. from 10-99 and then find all the numbers which are divisible by num.

Let us understand more of this with the help of examples −

Input − digit = 2, num= 12

Output − Count of n digit numbers divisible by given number: 8

Explanation − The 2-digit numbers divisible by 12 are 12, 24, 36, 48, 60, 72, 84 and 96, so there are 8 2 digit numbers divisible by 12.

Input − digit = 2, num= 9

Output − Count of n digit numbers divisible by given number − 10

Explanation − The 2 digit numbers divisible by 9 are 18, 27, 36, 45, 54, 63, 72, 81, 90 and 99 so there are 10 two digit numbers divisible by 9.

## Approach used in the below program as follows

• Take element digit and num as inputs.

• Assign a variable count as 0 to count the number of digits divisible by num.

• Declare and set digi_first as pow(10, digit - 1)

• Declare and set digi_last to pow(10, digit)

• Now declare and set d_first as digi_first % num and d_last as digi_last % num

• After finding d_first and d_last, set digi_first as (digi_first - d_first) + num and digi_last as digi_last - d_last

• Now set count to ((digi_last - digi_first) / num + 1).

• Return and print count.

## Example

Live Demo

#include <cmath>
#include <iostream>
using namespace std;
int main(){
int digit = 2 , num = 9;
//store the count
int count= 0 ;
int digi_first = pow(10, digit - 1);
int digi_last = pow(10, digit);
int d_first = digi_first % num;
int d_last = digi_last % num;
digi_first = (digi_first - d_first) + num;
digi_last = digi_last - d_last;
count = ((digi_last - digi_first) / num + 1);
cout<<"Count of n digit numbers divisible by given number: "<<count<<"\n";
return 0;
}

## Output

If we run the above code, we will get the following output −

Count of n digit numbers divisible by given number: 10

Updated on: 06-Jun-2020

275 Views