Given two numbers ‘a’ and ‘b’. Find the minimum difference between any terms in shifted infinite tables of ‘a’ and ‘b’, given shifts ‘x’ and ‘y’, where x, y >= 0.
Let us consider a = 6 and b = 16. Infinite tables of these numbers are.
Table of a : 6, 12, 18, 24, 30, 36, 42, 48.….
Table of b : 16, 32, 48, 64, 80, 96, 112, 128…..
Let given shifts be x = 5 and y = 2
Shifted Table of a : 11, 17, 23, 29, 35, 41, 47 …
Shifted Table of b : 18, 34, 50, 66, 82, 98, 114 …
The minimum difference between any two terms of above two shifted tables is 1 (See colored terms). So the output should be 1.
We strongly recommend you to minimize your browser and try this yourself first.
- Compute the Greatest Common Divisor (GCD) of the numbers ‘a’ and ‘b’. Let the GCD of two numbers be ‘g’.
- Compute the absolute difference “diff” of the shifts ‘x’ and ‘y’ under modulo ‘g’, i.e., diff = abs(a – b) % g
- The required shifted difference is minimum of ‘diff’ and ‘g – diff’.
Below is implementation of above algorithm.
Complexity: O(log n), to compute the GCD.
How does this work?
After shifting tables become (Assuming y > x and diff = y-x)
a+x, 2a+x, 3a+x, .. ab+x, …. and b+y, 2b+y, 3b+y, …., ab+y, ….
In general, difference is, abs[(am + x) – (bn + y)] where m >= 1 and n >= 1
An upper bound on minimum difference is “abs(x – y)”. We can always get this difference by putting m = b and n = a.
How can we reduce the absolute difference below “abs(x – y)”?
Let us rewrite “abs[(am + x) – (bn + y)]” as abs[(x – y) – (bn – am)]
Let the GCD of ‘a’ and ‘b’ be ‘g’. Let us consider the table of ‘g’. The table has all terms like a, 2a, 3a, … b, 2b, 3b, … and also the terms (bn – am) and (am – bn).
This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- How to swap two numbers without using a temporary variable?
- Program to find whether a no is power of two
- Lucky Numbers
- Program to find parity
- Ugly Numbers
- Write a program to add two numbers in base 14
- Minimum number of jumps to reach end
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Count of Binary Digit numbers smaller than N
- Find Union and Intersection of two unsorted arrays
- Program for Fibonacci numbers
- Average of a stream of numbers
- Add two numbers without using arithmetic operators
- To find sum of two numbers without using any operator