Skip to content

Instantly share code, notes, and snippets.

@rizemon
Created April 14, 2021 15:09
Show Gist options
  • Save rizemon/bdddc466511709e35dde077659b6ef43 to your computer and use it in GitHub Desktop.
Save rizemon/bdddc466511709e35dde077659b6ef43 to your computer and use it in GitHub Desktop.
Calculate GCD between 2 numbers and shows the working behind it
import sys
if len(sys.argv) < 3:
print("Usage: python test.py A B")
sys.exit(1)
A,B = int(sys.argv[1]), int(sys.argv[2])
if B < 0:
print("B should be positive.")
sys.exit(1)
if A < B:
if A < 0:
A, B = B, A
else:
A, B = B, A
backsub = []
r = 0
r_dict = {
"({})".format(A): "a",
"({})".format(B): "b"
}
def egcd(a, b):
global r
if a == 0:
return (b, 0, 1)
else:
r += 1
r_dict["({})".format(b%a)] = "r{}".format(r)
print("{} = {} x {} + {} --- r{} = {}".format(b, a,b//a, b%a, r, b%a))
output = "({}) = ({}) - {} x ({}) \n".format(b%a,b,b//a,a)
output += " = {} - {} x {}\n".format(b,b//a,a)
gcd, x, y = egcd(b % a, a)
output += " = {}\n".format(b%a)
backsub.append(output)
return (gcd, y - (b//a) * x, x)
print("="*30,"GCD Working","="*30)
gcd, x, y = egcd(A,B)
print("="*30,"Remainder Working","="*30)
for line in backsub[:0:-1]:
for sub in r_dict:
line = line.replace(sub, r_dict[sub])
print(line)
print("="*30,"Results","="*30)
print("gcd = {}".format(gcd))
print(" = ({})({}) + ({})({})".format(A,x,B,y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment