Count possible values of K such that A%K = B%K
Last Updated :
01 Feb, 2022
Given two integers A and B, the task is to count the possible values of K such that A%K = B%K. If the count is infinite, print -1.
Examples:
Input: A = 2, B = 4
Output: 2
Explanation: The set of all possible values of K is {1, 2}.
As 2%1 = 4%1 = 0 and 2%2 = 4%2 = 0.
Input: A = 5, B = 5
Output: -1
Explanation: There are infinite values of K as all possible integer value of K satisfies the given condition.
Approach: The given problem can be solved using the following observation that all values of A and B can be divided into the following two cases:
- The case where A = B. In such cases, all possible integer value of K is valid answer. Hence, the value of the required count is infinite.
- The case where A > B. In such cases, it can be observed that a value of K is valid if K divides (A – B). For cases with B > A, simply swap the values of A and B.
Therefore, calculate all the possible values of K such that it divides (A – B) completely which is the required value.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int countInt( int A, int B)
{
if (A == B)
return -1;
int diff = abs (A - B);
int count = 0;
for ( int i = 1; i * i <= diff; i++) {
if (diff % i == 0) {
if (diff == i * i)
count++;
else
count += 2;
}
}
return count;
}
int main()
{
int A = 2, B = 4;
cout << countInt(A, B);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static int countInt( int A, int B)
{
if (A == B)
return - 1 ;
int diff = Math.abs(A - B);
int count = 0 ;
for ( int i = 1 ; i * i <= diff; i++) {
if (diff % i == 0 ) {
if (diff == i * i)
count++;
else
count += 2 ;
}
}
return count;
}
public static void main (String[] args) {
int A = 2 , B = 4 ;
System.out.print(countInt(A, B));
}
}
|
Python3
def countInt(A, B):
if (A = = B):
return - 1 ;
diff = abs (A - B);
count = 0 ;
i = 1 ;
while ((i * i) < = diff):
if (diff % i = = 0 ):
if (diff = = i * i):
count + = 1
else :
count + = 2 ;
i + = 1
return count;
A = 2
B = 4
print (countInt(A, B));
|
C#
using System;
class GFG {
static int countInt( int A, int B)
{
if (A == B)
return -1;
int diff = Math.Abs(A - B);
int count = 0;
for ( int i = 1; i * i <= diff; i++) {
if (diff % i == 0) {
if (diff == i * i)
count++;
else
count += 2;
}
}
return count;
}
public static int Main()
{
int A = 2, B = 4;
Console.Write(countInt(A, B));
return 0;
}
}
|
Javascript
<script>
function countInt(A, B) {
if (A == B)
return -1;
let diff = Math.abs(A - B);
let count = 0;
for (let i = 1; i * i <= diff; i++) {
if (diff % i == 0) {
if (diff == i * i)
count++;
else
count += 2;
}
}
return count;
}
let A = 2, B = 4;
document.write(countInt(A, B));
</script>
|
Time Complexity: O(√(A – B))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...