Skip to main content
  1. Posts/

Find the GCF Between Two Numbers Version 2

·236 words·2 mins
Table of Contents

Hello I fixed my code so now it looks more better and cooler

Version 1 #

So here is version 1 when I use the recursive method meaning that it keeps calling itself so the things I change was mostly the inputs so now this code can ask the user to enter a two numbers.

# this program caculates the GCF of two numbers

print("Enter two numbers a and b to find the GCF gcf(a, b).")
a = int(input("a: "))
b = int(input("b: "))

# Version 1
# Using recursive method
def gcf(a, b):
    if b == 0:
        return a
    else:
        return gcf(b, a % b)
    
print(f"The GCF {a}, {b} is {gcf(a, b)}.")

Version 2 #

Here is version 2 this code uses the division based.

# this program caculates the GCF of two numbers

print("Enter two numbers a and b to find the GCF gcf(a, b).")
a = int(input("a: "))
b = int(input("b: "))

# Version 2
# division-based version
# Requirement: a > b otherwise it will not work
def gcf(a, b):
    assert a >= b, "ERROR: 'a' MUST BE GREATER THAN OR EQUAL TO '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 gcf().
if a >= b:
   answer = gcf(a, b)
else:
   answer = gcf(b, a)
  
print(f"The GCF {a}, {b} is {answer}.")