Find the minimum difference between Shifted tables of two numbers in Python


Suppose we have two numbers p and q, we have to find the minimum difference between any terms in the shifted infinite tables of p and q, these shifts are r and s, where r, s >= 0.

So, if the input is like p = 7 and q = 17, r = 6 and s = 3, then the output will be 0 as, table of 7 = [7, 14, 21, 28, 35, 42, 49, ...] and table of 17 = [17, 34, 51, 68, 85, 102, 119, ...], then shifted table of 7 will be [13, 20, 27, 34, 41, 48, 55, ...] and shifted table of 17 will be [20, 37, 54, 71, 88, 105, 121, ...], then the minimum difference between two terms of these shifted tables are 20-20 = 0.

To solve this, we will follow these steps −

  • g := gcd of (p, q)

  • difference := |r-s| mod g

  • return minimum of difference and g - difference

Example 

Let us see the following implementation to get better understanding −

import math
def get_minimum_diff (p, q, r, s):
   g = math.gcd(p,q)
   difference = abs(r-s) % g
   return min(difference, g - difference)
p = 7
q = 17
r = 6
s = 3
print(get_minimum_diff(p, q, r, s))

Input

7,17,6,3

Output

0

Updated on: 20-Aug-2020

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements