Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the minimum difference between Shifted tables of two numbers in Python
When we have two numbers p and q, we can create their multiplication tables and then shift them by values r and s respectively. The problem asks us to find the minimum difference between any terms in these shifted tables.
A shifted table means we add the shift value to each element in the multiplication table. For example, if we have the table of 7: [7, 14, 21, 28, ...] and shift it by 6, we get [13, 20, 27, 34, ...].
Understanding the Problem
Let's understand with an example where p = 7, q = 17, r = 6, and s = 3:
Table of 7: [7, 14, 21, 28, 35, 42, 49, ...]
Table of 17: [17, 34, 51, 68, 85, 102, 119, ...]
Shifted table of 7 (by 6): [13, 20, 27, 34, 41, 48, 55, ...]
Shifted table of 17 (by 3): [20, 37, 54, 71, 88, 105, 122, ...]
The minimum difference between terms is 20 - 20 = 0.
Algorithm
To solve this efficiently, we use the mathematical approach:
Calculate g = GCD of (p, q)
Find difference = |r - s| mod g
Return minimum of (difference, g - difference)
Implementation
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)
# Test with the example
p = 7
q = 17
r = 6
s = 3
result = get_minimum_diff(p, q, r, s)
print(f"Minimum difference: {result}")
Minimum difference: 0
How It Works
The key insight is that the shifted tables have a periodic pattern based on the GCD of p and q. Any element in the shifted table of p can be written as p * k + r, and any element in the shifted table of q can be written as q * j + s.
The difference between these elements is (p * k + r) - (q * j + s) = p * k - q * j + (r - s). Since gcd(p, q) divides both p and q, the minimum possible difference is determined by (r - s) mod gcd(p, q).
Testing with Another Example
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)
# Test with different values
test_cases = [
(7, 17, 6, 3),
(4, 6, 2, 5),
(10, 15, 3, 8)
]
for p, q, r, s in test_cases:
result = get_minimum_diff(p, q, r, s)
print(f"p={p}, q={q}, r={r}, s={s} ? Minimum difference: {result}")
p=7, q=17, r=6, s=3 ? Minimum difference: 0 p=4, q=6, r=2, s=5 ? Minimum difference: 1 p=10, q=15, r=3, s=8 ? Minimum difference: 0
Conclusion
The minimum difference between shifted multiplication tables can be calculated efficiently using the GCD of the two numbers. The algorithm runs in O(log(min(p, q))) time complexity due to the GCD calculation.
