Count possible values of K such that X – 1 and Y – 1 modulo K is same
Last Updated :
13 Sep, 2021
Given two numbers X and Y, the task is to find the count of integers K which satisfies the equation (X – 1) % K = (Y – 1) % K.
Examples:
Input: X = 2, Y = 6
Output: 3
Explanation:
K = {1, 2, 4} satisfies the given equation. Therefore, the count is 3.
Input: X = 4, Y = 9
Output: 2
Approach: Follow the steps below to solve the problem:
- The idea is to find the absolute difference between X and Y.
- Find the count of divisors of the calculated absolute difference and print the count as the required answer.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int condition( int a, int b)
{
int d = abs (a - b), count = 0;
for ( int i = 1; i <= sqrt (d); i++) {
if (d % i == 0) {
if (d / i == i)
count += 1;
else
count += 2;
}
}
return count;
}
int main()
{
int x = 2, y = 6;
cout << condition(x, y) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG{
static int condition( int a, int b)
{
int d = Math.abs(a - b), count = 0 ;
for ( int i = 1 ; i <= Math.sqrt(d); i++)
{
if (d % i == 0 )
{
if (d / i == i)
count += 1 ;
else
count += 2 ;
}
}
return count;
}
public static void main (String[] args)
{
int x = 2 , y = 6 ;
System.out.println(condition(x, y));
}
}
|
Python3
def condition(a, b):
d = abs (a - b)
count = 0
for i in range ( 1 , d + 1 ):
if i * i > d:
break
if (d % i = = 0 ):
if (d / / i = = i):
count + = 1
else :
count + = 2
return count
if __name__ = = '__main__' :
x = 2
y = 6
print (condition(x, y))
|
C#
using System;
class GFG{
static int condition( int a,
int b)
{
int d = Math.Abs(a - b), count = 0;
for ( int i = 1;
i <= Math.Sqrt(d); i++)
{
if (d % i == 0)
{
if (d / i == i)
count += 1;
else
count += 2;
}
}
return count;
}
public static void Main(String[] args)
{
int x = 2, y = 6;
Console.WriteLine(condition(x, y));
}
}
|
Javascript
<script>
function condition(a, b)
{
let d = Math.abs(a - b), count = 0;
for (let i = 1; i <= Math.sqrt(d); i++)
{
if (d % i == 0)
{
if (d / i == i)
count += 1;
else
count += 2;
}
}
return count;
}
let x = 2, y = 6;
document.write(condition(x, y));
</script>
|
Time Complexity: O(?abs(X – Y))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...