What is the fastest way to get prime numbers in python?

If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them.

Going by definition, a Prime number is a positive integer that is divisible only by itself and 1. For example: 2,3,5,7. But if a number can be factored into smaller numbers, it is called a Composite number. For example: 4=2*2, 6=2*3

And the integer 1 is neither a prime number nor a composite number. Checking that a number is prime is easy but efficiently checking needs some effort.

Method 1:

 
Let us now go with the very first function to check whether a number, say n, is prime or not. In this method, we will test all divisors from 2 to n-1. We will skip 1 and n. If n is divisible by any of the divisor, the function will return False, else True. 
Following are the steps used in this method: 

  1. If the integer is less than equal to 1, it returns False.
  2. If the given number is divisible by any of the numbers from 2 to n, the function will return False
  3. Else it will return True

Python3

import time

def is_prime[n]:

    if n

Chủ Đề