Determine if any number is prime

Source: Internet
Author: User

The prime number is also referred to as prime numbers , which is thenumber of natural numbers greater than 1, except 1 and the number itself, which cannot be divisible by other natural numbers (it can also be defined as only 1 and the number itself two factors). If the natural number greater than 1 is not prime, it is called composite.

Use Python to determine whether a number is prime.

The first method is divisible by dividing the number within the number range, the efficiency is very low, when the number is large time-consuming, the code realizes:

def is_prime (n):    if n = = 2:        return True    if n 2 = = 0 or n <= 1:        return False    sqr = Int (MATH.SQRT (n ) + 1    for divisor in range (3, SQR, 2):        if n% divisor = = 0:            return False    return True

The second approach is to use algorithms to optimize the entire logic and execution process, filtering out all primes within N, by defining an array, generating n*true elements, and implementing the Code:

def prime_sieve (n):    sieve_lst = [True] * n    sieve_lst[0] = False              # First and second not a prime number, set to False    sieve_lst[1] = False for              I in range (3, int (MATH.SQRT (n)) +1):        pointer = i                * # # of multiples within n digits, all set to False while        pointer < n:< C8/>sieve_lst[pointer] = False            pointer + = i           primes = [] for    x in range (n):        if sieve_lst[x]:            Primes.append (i)    print primes    return Primesprime_sieve (33) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

This algorithm comes from thebook "Hacking Secret ciphers with Python"

Determine if any number is prime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.