Count total divisors of A or B in a given range in C++


We are given four integers L, R, A and B. The goal is to find the count of numbers in range [L,R] that fully divide either A or B or both.

We will do this by traversing from L to R and for each number if number%A==0 or number%B==0 then increment count of divisors.

Let’s understand with examples.

Input − L=10, R=15, A=4, B=3

Output − Count of divisors of A or B − 2

Explanation

Number 12 is fully divisible by 3 and 4.
Number 15 is fully divisible by 3 only.
Total divisors=2

Input − L=20, R=30, A=17, B=19

Output − Count of divisors of A or B − 0

Explanation − No number between 20 and 30 fully divisible by A or B or both.

Approach used in the below program is as follows

  • We have taken four variables A, B, L and R.

  • Function countDivisors(int l, int r, int a, int b) takes all as input and returns the divisors of A or B or both that lie in range [L, R].

  • Take the initial count as 0.

  • Starting from i=L to i=R, if i%a==0 or i%b==0 increment count.

  • At the end of loop count as divisors of A or B.

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countDivisors(int l, int r, int a,int b){
   int count = 0;
   for (int i = l; i <= r; i++){
      if(i%a==0 || i%b==0)
         { count++ ; }
   }
   return count;
}
int main(){
   int L=5;
   int R=15;
   int A=2;
   int B=5;
   cout <<endl<< "Total divisors of A and B : "<<countDivisors(L,R,A,B);
   return 0;
}

Output

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

Total divisors of A and B : 7

Updated on: 29-Aug-2020

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements