The Euclidean Algorithm
def gcdEuclidean(a, b):
if a < b:
temp = a
a = b
b = temp
while b != 0:
r = a % b
a = b
b = r
return a
def lcmEuclidean(a, b):
gcd = gcdEuclidean(a, b)
return a * b / gcd
with open("gcd.txt",'r') as file:
lines = file.readlines()
print("%10s %10s %10s %10s" % ("a","b","gcd", "lcm"))
for line in lines:
pair = line.split()
a = int(pair[0])
b = int(pair[1])
gcd = gcdEuclidean(a, b)
lcm = a * b / gcd
print("%10d %10d %10d %10d" % (a, b, gcd, lcm))
Output:
a b gcd lcm
60 90 30 180
110 273 1 30030
220 1400 20 15400
315 825 15 17325
20 40 20 40
331 993 331 993
2091 4807 1 10051437
2475 32670 495 163350
67942 4209 23 12433386
490256 337 1 165216272