×

Python program to find the GCD or HCF

Python program to find the GCD or HCF

The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example, the HCF or GCD of 10 and 12 is 2.

Using Loop

The following is a source code that uses a loop to find the HCF or GCD of the two numbers:

 #Program to find GCD of two numbers 
 # define a function 
 def findGCD(a, b):  
 # choose the smaller number
     if a > b:  
         smaller = b  
else:  
         smaller = a  
     for i in range(1, smaller+1): 
         if((a % i == 0) and (b % i == 0)):
             GCD = i
     return GCD                              
 number1 = int(input("Enter the first number:"))
 number2 = int(input("Enter the second number:"))  
 print("The GCD of {0} and {1} is".format(number1, number2), findGCD(number1,    
 number2))

Output

Here is the result:

Python program to find the GCD

Explanation: In this program, we have stored two integers in a variable named number1 and number2, respectively. These numbers are passed to the function findGCD that computes the GCD of these two numbers and returns the result. In the function, we first determine the smaller of the two numbers since the GCD can only be less than or equal to the smallest number. We then use a loop to go from 1 to that number.

In each iteration, we will check if our number perfectly divides both the input numbers or not. If it divides perfectly, we store the number as GCD. After the iteration complete, the largest number that perfectly divides both the numbers will be displayed.

Using Euclidean Algorithm

This algorithm states that the GCD or H.C.F of two numbers divides their differences as well. In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the smaller by this remainder. This process is repeated until the remainder becomes 0.

Example: Suppose we want to find the H.C.F of 24 and 16, then we first divide 24 by 16. The remainder will be 8. Now, we divide 16 by 8, and the remainder is 0. So, the H.C.F of these two numbers is 8.

The following is the source code to get the GCD or HCF using Euclidean Algorithm:

 #Program to find GCD of two numbers using euclidean algorithm                                        
 # define a function   
 def findGCD(a, b):  
     while (b): 
         a, b = b, a % b 
     return a                                  
 number1 = int(input("Enter the first number:")) 
 number2 = int(input("Enter the second number:")) 
 print("The CGD of {0} and {1} is".format(number1, number2), findGCD(number1,   number2)) 

Output

Here is the result:

Python program to find the GCD

Explanation: In this program, we have stored two integers in variables named number1 and number2, respectively. We will iterate the loop until b becomes 0. The statement a, b = b, a % b does swapping of values in Python. After each iteration, we place the value of b in a and the remainder (a % b) in b, simultaneously. When b becomes zero, we will get H.C.F. in a.

Using Recursion

The following is source code to get the HCF or GCD using recursion:

 #Program to find GCD of two numbers using recursion   
 # define a function  
 def findGCD(a, b):    
     if (b == 0): 
         return a  else:  
         return findGCD(b, a % b)                                                                                                    
 number1 = int(input("Enter the first number:"))                                                                    
 number2 = int(input("Enter the second number:"))                                                                           
 print("The GCD of {0} and {1} is".format(number1, number2), findGCD(number1, number2))  

Output

Here is the result:

Python program to find the GCD

Explanation: In this program, we have stored two integers in variables named number1 and number2, respectively. These numbers will be passed to the recursive function findGCD(). If the second number is equal to 0, then the GCD of two numbers will be the first number. Else the recursive function will return the GCD of two numbers.


Related Topics

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

How to create a DataFrames in Python

How to create a DataFrames in Python Data Frame is a data structure in which data is stored in tabular form. They can also be referred as two-dimensional collection of data. Various...

5 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

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.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.