# Count numbers in range 1 to N which are divisible by X but not by Y in C++

We are provided a number N. The goal is to find the numbers that are divisible by X and not by Y and are in the range [1,N].

Let’s understand with examples.

Input

N=20 X=5 Y=20

Output

Numbers from 1 to N divisible by X not Y: 2

Explanation

Only 5 and 15 are divisible by 5 and not 10.

Input

N=20 X=4 Y=7

Output

Numbers from 1 to N divisible by X not Y: 5

Explanation

Numbers 4, 8, 12, 16 and 20 are divisible by 4 and not 7.

## Approach used in the below program is as follows

• We take an integer N.

• Function divisibleXY(int x, int y, int n) returns a count of numbers from 1 to N which are divisible by X and not Y.

• Take the initial variable count as 0 for such numbers.

• Traverse range of numbers using for loop. i=1 to i=n

• Now for each number i, check if ( i%x==0 && i%y!=0 ), if true increment count.

• Return the count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int divisibleXY(int x, int y, int n){
int count = 0;
for (int i = 1; i <= n; i++) {
if(i%x==0 && i%y!=0 )
{ count++; }
}
return count;
}
int main(){
int N = 100;
int X=6, Y=8;
cout <<"Numbers from 1 to N which are divisible by X and not Y: "<< divisibleXY(X,Y,N);
return 0;
}

## Output

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

Numbers from 1 to N which are divisible by X and not Y: 12