Count of all possible values of X such that A % X = B
Given two integers A and B. The task is to find the count of all possible values X such that A % X = B. If there are an infinite number of possible values then print -1.
Examples:
Input: A = 21, B = 5
Output: 2
8 and 16 are the only valid values for X.
Input: A = 5, B = 5
Output: -1
X can have any value > 5
Approach: There are three possible cases:
- If A < B then no value of X can satisfy the given condition.
- If A = B then infinite solutions are possible. So, print -1 as X can be any value greater than A.
- If A > B then the number of divisors of (A – B) which are greater than B is the required count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countX( int a, int b)
{
if (b > a)
return 0;
else if (a == b)
return -1;
else {
int x = a - b, ans = 0;
for ( int i = 1; i * i <= x; i++) {
if (x % i == 0) {
int d1 = i, d2 = b - 1;
if (i * i != x)
d2 = x / i;
if (d1 > b)
ans++;
if (d2 > b)
ans++;
}
}
return ans;
}
}
int main()
{
int a = 21, b = 5;
cout << countX(a, b);
return 0;
}
|
Java
class GFG
{
static int countX( int a, int b)
{
if (b > a)
return 0 ;
else if (a == b)
return - 1 ;
else
{
int x = a - b, ans = 0 ;
for ( int i = 1 ; i * i <= x; i++)
{
if (x % i == 0 )
{
int d1 = i, d2 = b - 1 ;
if (i * i != x)
d2 = x / i;
if (d1 > b)
ans++;
if (d2 > b)
ans++;
}
}
return ans;
}
}
static public void main (String args[])
{
int a = 21 , b = 5 ;
System.out.println(countX(a, b));
}
}
|
Python 3
def countX( a, b):
if (b > a):
return 0
elif (a = = b):
return - 1
else :
x = a - b
ans = 0
i = 1
while i * i < = x:
if (x % i = = 0 ):
d1 = i
d2 = b - 1
if (i * i ! = x):
d2 = x / / i
if (d1 > b):
ans + = 1
if (d2 > b):
ans + = 1
i + = 1
return ans
if __name__ = = "__main__" :
a = 21
b = 5
print (countX(a, b))
|
C#
using System;
class GFG
{
static int countX( int a, int b)
{
if (b > a)
return 0;
else if (a == b)
return -1;
else
{
int x = a - b, ans = 0;
for ( int i = 1; i * i <= x; i++)
{
if (x % i == 0)
{
int d1 = i, d2 = b - 1;
if (i * i != x)
d2 = x / i;
if (d1 > b)
ans++;
if (d2 > b)
ans++;
}
}
return ans;
}
}
static public void Main ()
{
int a = 21, b = 5;
Console.WriteLine(countX(a, b));
}
}
|
Javascript
<script>
function countX(a, b)
{
if (b > a)
return 0;
else if (a == b)
return -1;
else {
let x = a - b, ans = 0;
for (let i = 1; i * i <= x; i++) {
if (x % i == 0) {
let d1 = i, d2 = b - 1;
if (i * i != x)
d2 = parseInt(x / i);
if (d1 > b)
ans++;
if (d2 > b)
ans++;
}
}
return ans;
}
}
let a = 21, b = 5;
document.write(countX(a, b));
</script>
|
Time Complexity: O(sqrt(a – b))
Auxiliary Space: O(1)
Last Updated :
30 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...