Count integers in the range [A, B] that are not divisible by C and D
Last Updated :
15 Nov, 2022
Given four integers A, B, C and D. The task is to find the count of integers in the range [A, B] that are not divisible by C and D .
Examples:
Input: A = 4, B = 9, C = 2, D = 3
Output: 2
5 and 7 are such integers.
Input: A = 10, B = 50, C = 4, D = 6
Output: 28
Approach: First include all the integers in the range in the required answer i.e. B – A + 1. Then remove all the numbers which are divisible by C and D and finally add all the numbers which are divisible by both C and D.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countNums( int a, int b, int c, int d)
{
int x = b / c - (a - 1) / c;
int y = b / d - (a - 1) / d;
int k = (c * d) / __gcd(c, d);
int z = b / k - (a - 1) / k;
return b - a + 1 - x - y + z;
}
int main()
{
int a = 10, b = 50, c = 4, d = 6;
cout << countNums(a, b, c, d);
return 0;
}
|
Java
class GFG
{
static int countNums( int a, int b, int c, int d)
{
int x = b / c - (a - 1 ) / c;
int y = b / d - (a - 1 ) / d;
int k = (c * d) / __gcd(c, d);
int z = b / k - (a - 1 ) / k;
return b - a + 1 - x - y + z;
}
static int __gcd( int a, int b)
{
if (b == 0 )
return a;
return __gcd(b, a % b);
}
public static void main(String []args)
{
int a = 10 , b = 50 , c = 4 , d = 6 ;
System.out.println(countNums(a, b, c, d));
}
}
|
Python3
from math import gcd
def countNums(a, b, c, d) :
x = b / / c - (a - 1 ) / / c;
y = b / / d - (a - 1 ) / / d;
k = (c * d) / / gcd(c, d);
z = b / / k - (a - 1 ) / / k;
return (b - a + 1 - x - y + z);
if __name__ = = "__main__" :
a = 10 ; b = 50 ; c = 4 ; d = 6 ;
print (countNums(a, b, c, d));
|
C#
using System;
class GFG
{
static int countNums( int a, int b, int c, int d)
{
int x = b / c - (a - 1) / c;
int y = b / d - (a - 1) / d;
int k = (c * d) / __gcd(c, d);
int z = b / k - (a - 1) / k;
return b - a + 1 - x - y + z;
}
static int __gcd( int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static void Main(String []args)
{
int a = 10, b = 50, c = 4, d = 6;
Console.WriteLine(countNums(a, b, c, d));
}
}
|
Javascript
<script>
function countNums(a, b, c, d)
{
let x = parseInt(b / c) - parseInt((a - 1) / c);
let y = parseInt(b / d) - parseInt((a - 1) / d);
let k = parseInt((c * d) / __gcd(c, d));
let z = parseInt(b / k) - parseInt((a - 1) / k);
return b - a + 1 - x - y + z;
}
function __gcd(a, b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
let a = 10, b = 50, c = 4, d = 6;
document.write(countNums(a, b, c, d));
</script>
|
Time Complexity: O(log(min(c, d)), where c and d are the given inputs.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...