Python Program to find GCD of Two Numbers

Find the GCD of Two Numbers

In this Python Program find the GCD of Two Numbers which numbers are entered by the user. Basically the GCD of two number is the largest positive integer that divides each of the integers where the user entered number should not be zero.

Let up suppose, we have two numbers, 36 and 60

36 = 2 * 2 * 3 * 3

60 = 2 * 2 * 3 * 5

GCD = Multiplication of Common factors

GCD = 2 * 2 * 3

GCD = 12

Python Program to find GCD of Two Numbers

Working:

Step 1. Start

Step 2. Take two user input and store into int type variable. such as num1 and num2.

Step 3. Define a function name as gcdFunction(num1, num2) with arguments num1 and num2.

Step 4. Now, check if num1 > num2, then store num2 value in small variable.

Step 5. Else, Store num1 value in small variable.

Step 6.  Run a for loop starts from 1 to small + 1.

Step 7. Inside the for loop, check num % i == 0 and num2 % i == 0. If both conditions are true then only assign i variable value to gcd variable.

Step 8. Outside for loop, print gcd value.

Step 9. Call gcdFunction() function with arguments num1 and num2.

Stop 10. Stop

Python Program:

num1 = int(input("Enter First Number:"))
num2 = int(input("Enter Second Number:"))


def gcdFunction(num1, num2):
    if num1 > num2:
        small = num2
    else:
        small = num1
    for i in range(1, small+1):
        if (num1 % i == 0) and (num2 % i == 0):
            gcd = i
    print("GCD of two Number: {}".format(gcd))

gcdFunction(num1, num2)


# This code is contributed by Shubhanshu Arya (Prepinsta Placement Cell Student) 

Output:

Enter First Number:36
Enter Second Number:40
GCD of two Number: 4