Count of m digit integers that are divisible by an integer n in C++

C++Server Side ProgrammingProgramming

We are given two integers m and n. The goal is to count m digit numbers that are divisible by n.

If m=1, then numbers are 0,1,2,3,4,5,6,7,8,9 and n=3 then numbers divisible by 3=0,3,6,9 count=4.

Let’s understand with examples.

Input − m=2, n=9

Output − Count of m digit numbers divisible by n − 10

Explanation − between 10 and 99 numbers divisible by 9 are −

18, 27, 36, 45, 54, 63, 72, 81, 90, 99

Input m=3, n=300

Output − Count of m digit numbers divisible by n: 3

Explanation − between 100 and 999 numbers divisible by 300 are −

300, 600, 900

Approach used in the below program is as follows

  • We take integers m and n.

  • Calculate largest m-1 digit number as num1

  • Calculate largest m digit number as num2

  • Function findCount(int n, int L, int R) takes n and range ( between num1 and num2 ) as input and returns all numbers in that range which are divisible by n.

  • Take the initial count as 0.

  • Starting from i=L to i=R. If i%n==0, increment count.

  • Return count as result.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
// Returns count of m digit numbers having n
// as divisor
int findCount(int n, int L, int R){
   int count=0;
   int i;
   for(int i=L;i<=R;i++){
      if(i%n==0)
         { count++; }
   }
   return count;
}
int main(){
   int M = 2, N = 9;
   int i;
   int num1 = 0; //largest m-1 digit no.
   for (i = 0; i < (M - 1); i++)
      num1 = (num1 * 10) + 9;
   int num2 = 0; //largest m digit no.
   for (i = 0; i < M; i++)
      num2 = (num2 * 10) + 9;
   cout<<"Count of M digit no.s divisible by N:"<<findCount(N,num1+1,num2);
   return 0;
}

Output

If we run the above code it will generate the following output−

Count of M digit no.s divisible by N:11
raja
Published on 29-Aug-2020 15:35:05
Advertisements