Find GCF of Two Numbers
Table of Contents
Hello in this blog I will show you how to write a program that tells you the greatest common factor or GCF here is two ways you can do it.
This is version 1 #
this method uses the recursive method meaning it keeps calling itself.
# find GCF of two numbers
input("Enter two numbers to find the GCF: ")
print(input)
a = 2 # 1, 2, 3, 6
b = 4 # 0, 1, 2, 3, 4, 5, 6, 6, 7, 9, ... infinity
# Version 1
# Using recursive method
gcd(a, b) = 3
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
print(f"The HCF({a}, {b}) is : {gcd(a, b)}")
Version 2 #
this code uses the division based code
# Version 2
# division-based version
# Requirement: a > b otherwise it will not work
def gcd(a, b):
assert a >= b, "a must be bigger than b"
while b != 0:
t = b
b = a % b
a = t
return a
# You need to make sure to check a and b before running gcd().
if a >= b:
answer = gcd(a, b)
else:
answer = gcd(b, a)
print (f"The gcd of {a} and {b} is: ({answer})")
try the two method see which one you like.ss