SQRT in Python

Python has an in-built function sqrt which accepts a number as an input and returns the square root of that number as an output. You need to import the math module to access this function directly and you have to call this function using math.

Syntax:

math.sqrt(n)

Parameters:

Any number n, n>=0

Output:

The output is the square root of the number n, passed as the input parameter.

Example of Python sqrt usage:

import math

#

perfect square

 number
print(math.sqrt(9))

# Checking for 0 to see if there is an error
print(math.sqrt(0))

# Not a

perfect square

print(math.sqrt(35))

# Float number
print(math.sqrt(22.5))
3.0
0.0
5.916079783099616
4.743416490252569

For negative numbers, we will get an error.

>>> math.sqrt(-18)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Practical Application:

A prime number is a number which is divisible only 1 and the number itself. If you are a beginner, let’s write a code to check if the number is prime or not. Let’s not worry about optimization for now.

If your code is different from mine no worries. Check this piece of code to print the time taken to run the code.

import time

start_time = time.time()
print("--- %s seconds ---" % (time.time() - start_time))
import time

def prime_or_not(n):
    count=0
    for i in range(2,n):
        if n%i==0:
            count+=1
    if count==0:
        print('prime')
    else:
        print('non prime')

start_time = time.time()
prime_or_not(12345397)
print("--- %s seconds ---" % (time.time() - start_time))

In the above code, what we are checking is, if the number is divisible by any number in between 2 and n-1 then the number is Prime number. Else it’s not a prime number.

The time took by the above program to check if the number 12345397 is prime or not is:

prime
--- 8.480168104171753 seconds ---

Optimized Python code using sqrt:

You can optimize the above code, by checking if the number is divisible between 2 and the square root of the number. Now modify the for loop limits and check the time taken:

import time
import math

def prime_or_not(n):
    count=0
    for i in range(2,int(math.sqrt(n))):
        if n%i==0:
            count+=1
    if count==0:
        print('prime')
    else:
        print('non prime')

start_time = time.time()
prime_or_not(12345397)
print("--- %s seconds ---" % (time.time() - start_time))

Now the output is:

prime
--- 0.0020029544830322266 seconds ---

You can see there is a big difference in the time taken to run the code.

Translate ยป