A simple GCF calculator in Python

It takes two numbers as input, checks if they are integers, and then finds the greatest common factor. The process involves creating a list of factors for each number and determining the highest common factor. Alternatively, I could use sets for a more efficient solution.



# GCF calculator
print("GCF calculator")
def calculate_gcf(num1, num2):
    gcf1List = []
    gcf2List = []

    for i in range(1, num1 + 1):
        if num1 % i == 0:
            gcf1List.append(i)

    for i in range(1, num2 + 1):
        if num2 % i == 0:
            gcf2List.append(i)

    common_factors = set(gcf1List) & set(gcf2List)
    gcf = max(common_factors)

    return gcf

'''
# or this
def calculate_gcf(num1, num2):
    factors1 = {i for i in range(1, num1 + 1) if num1 % i == 0}
    factors2 = {i for i in range(1, num2 + 1) if num2 % i == 0}

    common_factors = factors1 & factors2
    gcf = max(common_factors)

    return gcf
'''

while True:
    try:
        num1 = int(input("What is the first number: "))
        num2 = int(input("What is the second number: "))
        result = calculate_gcf(num1, num2)

    except ValueError:
        print("Please enter two integers.")
        continue


    print(f"The GCF between {num1} and {num2} is {result}")
    print()


Categories: Project

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *