×

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 Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

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

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute 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.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 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 Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Introducing modern python computing in simple packages

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

3 minutes read.

Python Marshmallow

Python:  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 is said...

3 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.