6 Best Ways to Compute HCF or GCD in Python

6 Best Ways to Compute HCF or GCD in Python

GCD Python: In this article, we have discussed different ways of computing GCD of two numbers in Python.

Note that GCD stands for Greatest Common Divisor.

GCD also called as HCF(Highest Common Factor).

We can calculate GCD by using Recursion Function, Loops, Euclidean algorithm, Math, Fractions and Numpy libraries.

What is GCD?

GCD is nothing but Greatest Common Divisor or Highest Common Factor of input numbers.

The Largest Integer will divide and return the difference.

For example, The GCD of 14 and 16 is 2.

Different Ways to Compute GCD

GCD can be computed by following ways.

  • Using Recursion Function
  • Leveraging Loops
  • Using Euclidean Algorithm
  • With math.gcd() Function

Using Recursion Function

Recursion is nothing but a mechanism in which a function calls itself.

Using recursion program, solution to the bigger problem is mentioned in terms of smaller problems.

Lets go through the implementation below.

def recursiveGCD(a,b): 
        return a 
        return recursiveGCD(b,a%b)  
print("The GCD is", recursiveGCD(a, b))

The GCD is 18

Leveraging Loops

Lets compute GCD by leveraging the loop.

def loopGCD(a, b): 
    if a > b: 
        tiny = b 
        tiny = a 
    for j in range(1, tiny+1): 
        if((a % j == 0) and (b % j == 0)): 
            finalgcd = j 
    return finalgcd 

print("The GCD is", loopGCD(a, b))

The GCD is 18

You May Also Like,

Using Euclidean Algorithm

Mathematically Euclidean Algorithm is an impressive way for computing the greatest common divisor (GCD) of two numbers (integers), where the largest number that divides both without having a remainder.

This Algorithm is named after the ancient Greek mathematician Euclid.

Using Euclidean Algorithm, we can compute GCD by leveraging as below.

def algoGCD(a, b): 
       a, b = b, a % b 
   return a 


print("The GCD is", algoGCD(a, b))

The GCD is 18

With math.gcd() Function

The math package provides gcd() method , which will compute the gcd of given numbers.

Its just a one line code.

import math 

print("The GCD is", math.gcd(a, b))

The GCD is 18

Using fractions.gcd() Function

The fractions package provides gcd() method, this will calculate the gcd with one line of code.

import fractions
print("The GCD is", fractions.gcd(a, b))

The GCD is 18

You May Also Love,

Using numpy.gcd() Function

The numpy package provides gcd() method, using this we can compute the gcd with one line of code.

Note that gcd() method is added into numpy library from version 1.15.

So if your using any version older than 1.15, then gcd function will not be available.

import numpy


print("The Value is", numpy.gcd(a,b))

The GCD is 18


Above are the some of the best methods to compute GCD in Python.

To conclude this tutorial, we covered various methods with examples to calculate HCF of two numbers using Python progamming language.

Python Remove Character From String: Learn How To Remove On Python

Python Remove Character From String: Learn How To Remove On Python

Python Remove Character From String: In this article, we have discussed how can you remove the character from string in python.

Let’s discuss how to remove a specific character or unwanted character from string in this post.

The following are the different string methods to remove the character from a string element using python programming.

As String is immutable, the methods used below will return a new string and the original string remains unchanged.

In other words, we are just doing string manipulation to achieve the result.

Python Remove Character From String

In this article of python remove character, we have discussed all the steps and methods how can you remove it in python.

Read this article fully, and if you have any doubts dont hesitate to ask us on the comments section.

You can also rate us on the bottom-left section of the vote.

Using the translate method

Python translate() method replaces each character in the given string inline to the provided translation table.

for this, we have to provide the Unicode for the character and None as replacement value to remove the value from the final string.

ord() function used to retrieve the Unicode of a character.

Let’s write a Python program to remove a character in the string using translate function.

inputValue = 'xyz987zyx'
result = inputValue.translate({ord(i): None for i in 'xyz'});


Using the replace method

Python replaces() method replaces character with a given replacement character.

so we can provide the replacement character as empty “” or whitespace, then the character will be removed.

Let’s write a Python program to remove the first character in the original string using replace() function.

inputValue = 'Tracedynamics'
result = inputValue.replace('T', '');


As per the output above, we can see in the new string the character ‘T’ is removed.

similarly, if you want to remove the last character, then substitute the replace method with ‘s’ character.

You May Like,

Remove string number of times

replace() method accepts a third parameter or argument.

This parameter can be no of times a specified string can be replaced.

In the below program, let provide an empty string to remove the specified characters using replace() function.

inputValue = 'Tracedynamics'
result = inputValue.replace('a', '', 2);


Remove newline from string

We can remove a newline from python string using replace() method in the below example.

if there is any whitespace character, we can also remove using replace() method.

inputValue = 'Trace\ndyna\nmics'
result = inputValue.replace('\n', '');


Removing substring from a string

We can remove a certain part of a string(substr) using replace() method.

inputValue = 'Tracedynamics'
result = inputValue.replace('dynamics', '');


You May Also Love,

Remove space from a string

Let’s remove space from a string using replace() method in the below example.

inputValue = 'T r a c e'
result = inputValue.replace(' ', '');


for removing any special characters, we can use the regex pattern(regular expression) in the replace method.

To conclude this tutorial, we covered various types of implementation to remove a character from string using Python Programming.

Sleep() Python Method

Sleep() Python Method

sleep python method pauses/suspends the python program for certain amount of specified time.In other words, sleep method suspends the execution of the calling thread for a given number of seconds.

The method argument can be a floating point to specify a more precise sleep time.Also note that, the actual suspension time might be less than the requested time. Its because of any caught signal which will terminate the sleep() following execution.

Python time.sleep( ): time sleep method is similar to shell sleep command. It accepts the argument in seconds/milli seconds.

For precise sleep times, floating point number can be provided as the argument for python time sleep() method.

Note: time sleep method is part of time module/package in python 2 and python 3, so you need to import the “time” package in the respective python script or function.

Since python version 3.5, the sleep function now sleeps atleast seconds eventhough if the sleep is interrupted by a signal, except incase of signal handler raises an exception via script.

Syntax of Python time.sleep( ):

Following is the syntax for sleep method

time.sleep( t )


t – Number of seconds/milliseconds execution to be suspended in python code.

Example 1:

Following example program illustrates the exact usage of time sleep( ) method in the python script or function.

import time 
# Print the start time  
print("current time start: ", end ="") 
# using sleep() to pause the code execution 
# Print the end time  
print("current time end: ", end ="") 


current time start: Wed May 29 16:50:48 2019
current time end: Wed May 29 16:50:53 2019

As per the program execution, the wait time or delay is 5 seconds.

Example 2: Delay in Python script

Create a script called sleep-demo.py:

# The program will run infinity times on screen till user hit the CTRL+C
# The program will sleep for 10 seconds before updating date and time again.
import time
print "!!! Hit CTRL+C to stop the program !!!"
## Start loop ##
while True:
        ### Show today's date and time ##
	print "Current date & time " + time.strftime("%c")
        #### Delay for 10 seconds ####

Save, close the file and run as follows:
$ chmod +x sleep-demo.py
$ ./sleep-demo.py


Current date & time Wed May 29 17:50:48 2019
Current date & time Wed May 29 17:50:58 2019
Current date & time Wed May 29 17:51:08 2019
Current date & time Wed May 29 17:51:18 2019
Current date & time Wed May 29 17:51:28 2019
Current date & time Wed May 29 17:51:38 2019

The output will be infinite loop till user interrupts(CTRL+C).

Example 3: Python Multithreading

Python supports multithreading too, here’s an example of a multithreaded Python program.

Create a script called multithread-demo.py:


    import threading 
    import time
    def print_welcome():
      for i in range(3):
    def print_python(): 
        for i in range(3): 
    t1 = threading.Thread(target=print_welcome)  
    t2 = threading.Thread(target=print_python)  

As per the above program, execution suspended for two threads at 0.6 seconds and 0.9 seconds respectively.
So start exploring python sleep function in your python script, Happy scripting 🙂

Pin It on Pinterest