×

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

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Python Interpreter

In this tutorial, we will go through the basic knowledge about what an interpreter is and how we use it in the python programming language. It is one of the...

3 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.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.