• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python isprime – Function for Determining if Number is Prime

Python isprime – Function for Determining if Number is Prime

February 7, 2022 2 Comments

Finding out if a number is prime is easy to do in Python. We can determine if a number is prime if it has no factors between 2 and the square root of the number.

Below is a function which will determine if a number is prime in Python.

def isPrime(n):
    if (n <=  1):
        return False
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True

When working with numbers, sometimes it can be useful to know if a number is prime or not.

We can find if a number is prime easily in Python with the help of the division method for prime factorization.

To determine if a number is a prime number, we need that only the number and 1 can divide the number. To check this, we need to do the following:

First, if the given number is even, then we know that 2 divides the number and the number is not prime.

Next, we need to loop through the odd numbers 3 until the square root of the number to see if there are any numbers which can divide our number.

Why are we doing this?

First, we only need to check odd numbers because if the number is even, then the function will have returned “False” in the first step. Second, we only need to check until the square root of the temporary number because of the statement: Every composite number has at least one prime factor less than or equal to the square root of itself.

Below is the final function to find out if a number if a prime number using Python.

def isPrime(n):
    if (n <=  1):
        return False
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True

Determining if a Number is Prime Using Python

We can now use our function for seeing if a number is a prime number to determine if various numbers or primes or not.

Let’s look and see if there are primes for a handful of numbers in the following example.

def isPrime(n):
    if (n <=  1):
        return False
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True
        
print(isPrime(10))
print(isPrime(13))
print(isPrime(90))
print(isPrime(121))
print(isPrime(749))
print(isPrime(283))

#Output:
False
True
False
False
False
True

Finding the First n Primes in Python

Let’s use our isPrime() function to find the first n primes, given n, in Python.

To find the first n primes, we will loop from 2 until we have n primes.

Below is a Python function which will return the first n primes.

def getPrimes(n):
    primes = [2]
    num = 3
    while (len(primes) < n):
        if(isPrime(num)):
            primes.append(num)
        num = num + 2
    return primes

For example, if we want to find the first 10 prime numbers, we can do so in the following Python code.

def getPrimes(n):
    primes = [2]
    num = 3
    while (len(primes) < n):
        if(isPrime(num)):
            primes.append(num)
        num = num + 2
    return primes

#Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

If we want to find the first 20 prime numbers, we can call our function with 20.

def getPrimes(n):
    primes = [2]
    num = 3
    while (len(primes) < n):
        if(isPrime(num)):
            primes.append(num)
        num = num + 2
    return primes

#Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]

Hopefully this article has been useful for you to learn how to determine if a number is prime in Python.

Other Articles You'll Also Like:

  • 1.  math gcd Python – Find Greatest Common Divisor with math.gcd() Function
  • 2.  Using Python to Create Empty DataFrame with pandas
  • 3.  Sort a List of Strings Using Python
  • 4.  Remove Duplicates from Sorted Array in Python
  • 5.  How to Check if List is Empty in Python
  • 6.  Change Column Name in pandas DataFrame
  • 7.  Create Symbolic Link with Python os.symlink() Function
  • 8.  Python Factorial Recursion – Using Recursive Function to Find Factorials
  • 9.  Divide Each Element in List by Scalar Value with Python
  • 10.  Create List of Numbers from 1 to 100 Using Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Comments

  1. Jean KOUSSAWO says

    May 23, 2022 at 9:50 am

    Hi. Nice job. I just noticed 2 issues with the function ‘isPrime’.
    – First, if someone passes a negative number, an error will occur because of the n**0.5.
    – Second, 1 pass through the function as a prime number. But modern mathematicians don’t accept it like that. Here is a link that briefly explains that: https://www.wgtn.ac.nz/science/ask-a-researcher/is-1-a-prime-number.

    Thank you for sharing this program. It helped me save some time. Wish you correct that issues.

    Reply
    • Erik says

      May 23, 2022 at 2:06 pm

      You are welcome, thanks for the comments. I’ve updated the function which will cover the two issues you’ve presented. The first is just simple data validation but I’ve wrapped one and two into just one if statement.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy

x