×

Python Program to Find the gcd of Two Numbers

Introduction

Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is used to determine the HCF (Highest Common Factor).

The Goal of the Article

  1. This post will teach you how to use Python to determine the GCD of two numbers.
  2. This article explains the mathematical definition of GCD and shows how to use Python to implement it.
  3. We will go over different ways to use
    • gcd() function
    • recursion
    • loops
    • Euclidean Algorithmto compute the GCD of two values.
  4. In GCD, managingnegative numbers

Overview of GCD of Two Digits in Python

The mathematical term GCD (Greatest Common Divisor) describes finding the biggest common factor between two values. The greatest positive integer that divides two or more numbers that aren't all zeros is called the GCD.

HCF is another name for GCD (Highest Common factor).

We will demonstrate how to compute the GCD of two digits in this example. Example: The numbers 4 and 10 are both presents. What are 4 and 10's GCD/HCF?

We will talk about the greatest common factor that divides two integers as we review the notion of GCD. The biggest common factor between 4 and 10 is 2.

GCD Calculation with the gcd() Function

The GCD of two digits can be calculated in a number of ways. Utilizing the math module's gcd() function is one of the techniques.

Note: To use the gcd() function to determine the gcd of two numbers. The math module must be imported. Themathmodule will raise an import error if it is not imported.

Syntax: GCD function syntax is as follows:

math.gcd(x, y)

Parameters:

The GCD/HCF for the non-negative integer x "x" must be calculated.

Another non-negative number whose GCD/HCF we must calculate is y 'y'.

The highest common factor, or GCD of x,y, will be returned by the math.gcd() function as a non-negative integer as the return type.

Remark: If we entered both x and y as 0, then. If we use any other data type than int, the function will throw a TypeError and return 0.

For example:

# GCD method can be found in the math module.
import math


# Let's now determine the gcd of two numbers.
a = 50
b = 10
HCF = math.gcd(a,b)


print(f"The GCD of {a} and {b} is {HCF}.")

Output:

The GCD of 50 and 6 is 2.

Recursion is Used to Determine the GCD

The GCD of two numbers will now be calculated using the recursion technique.

For example:

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a%b)


print(gcd(100,3))

Output:

1

Explanation: let’s consider a and b are two variables. Firstly, create a function which is gcd() and passed two arguments. Then in the first condition, if “b” is equal to 0 then return the value of “a” otherwise call gcd() function in which the first argument is "b" and the second argument is "x%y". Finally, print in which call the function with a valid argument.

Calculating the GCD using the Euclidean Algorithm

The most effective approach for calculating the GCD of two digits is the Euclidean Algorithm.

Thus, according to the Euclidean method, we must first store the larger and smaller numbers before dividing the larger number by the lower number and storing the result.

Divide the stored remainder by a smaller integer, then continue the operation until the remaining equals 0.

Example: The numbers 24 and 54 are given. We now divide 54%24 to get 6 and store 6, in accordance with the Euclidean Algorithm. Divide 24%6 now to get 0. We now have no remaining. Consequently, the GCD of 24 and 54 is 6, which is our finding.

Using LOOPS:

For example:

a = 56
b = 108
while b:
a, b = b, a%b
print(a)

Output:

4

Using Recursion:

For example:

def gcd(a, b):
    if a == b or b == 0:
        return a
    if a == 0:
        return b


    else:
        if a>b:
            return gcd(a-b, b)
        else:
            return gcd(a, b-a)


print(gcd(27,90))

Output:

9

Using Loops to Calculate the GCD:

For example:

a = 24
b = 100
n = min(a, b)


HCF = 0
for j in range(1,n+1):
    if a%j == 0 and b%j == 0:
HCF = j


print (HCF)

Output:

4

Explanation:

The HCF (highest common factor) of two digits always resides between 1 and the minimum of two numbers, which is why n stores the least value of a and b values. The lowest value of two digits can thus be stored in n.

Due to the for loop's exclusive use of n+1, it will execute for n+1 times. Verify that both values may be divided by the present value at each step. If the present value of the for loop divides both values, the present value of the for loop will be HCF. The HCF (highest common factor) of a and b will be returned by our software following the successful completion of the for a loop.

In GCD, managing negative numbers:

Since the GCD of two integers can never be negative, if any of the numbers are negative, change them to positive by multiplying them by -1.

Return and if b is equal to 0.

Otherwise, call the method for value b, a%b, recursively, and return.

Code:

# This technique raises the bar for repeated subtraction.
# Use the Euclidean algorithm's modulo operator effectively
def get_GCD(a, b):
    return b == 0 and a or get_GCD(b, a % b)




num_1 = -42
num_2 = 50


# Changing a negative number to a positive if the user enters one
# GCD is the largest real integer that divides both numbers, according to its definition.
# -42&50: GCD = 12 (as greatest num that divides both)
# -42& -50: GCD = 12 (as greatest num that divides both)
num_1 >= 0 and num_1 or -num_1
num_2 >= 0 and num_2 or -num_2


print("GCD of", num_1, "and", num_2, "is", get_GCD(num_1, num_2))

Output:

GCD of -42 and 50 is 2

Conclusion

A mathematical instrument called GCD provides information on the greatest common factor between two numbers.

To determine the gcd of two numbers, we can use the developed gcd() method, which is accessible in the math module.

One of the most used algorithms, the Euclidean Algorithm, can be used to determine the GCD.


Related Topics

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

3 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.