This article describes how to use Python to determine prime numbers, python, which is often used for scientific computation, can handle this small problem. Of course, you can refer to the subprime number or prime number as needed. In a natural number greater than 1, except for 1 and the integer itself, it cannot be divisible by other natural numbers. Prime numbers play an important role in number theory. A number larger than 1 but not a prime number is called a union number. 1 and 0 are both non-prime numbers and non-composite numbers. Prime numbers are two concepts that are opposite to Union numbers. They constitute one of the most basic definitions in number theory. The problems created based on the definition of prime numbers have many world-class problems, such as the godebach conjecture. The basic arithmetic theorem proves that each positive integer greater than 1 can be written as the product of a prime number, and the product form is unique. The important point of this theorem is that 1 is excluded from the prime number set. If 1 is considered as a prime number, these strict interpretations have to add some restrictions. A friend occasionally asked python how to determine the prime number, checked it online, and summarized several methods for the python script to determine whether a number is a prime number:
1. Use python mathematical functions
import math def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True
2. Single-line program scanning prime numbers
from math import sqrt N = 100 [ p for p in range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]
Use the itertools module of python
from itertools import count def isPrime(n): www.jb51.net if n <= 1: return False for i in count(2): if i * i > n: return True if n % i == 0: return False
3. Two methods without using modules
Method 1:
def isPrime(n): if n <= 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True
Method 2:
def isPrime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True
Eg: Obtain the prime number between 20001 and 40001)
Since it can only be rounded out by one or itself, it means that when the remainder of two times is 0, the Code is as follows:
#!/usr/bin/pythonL1=[]for x in xrange(20001,40001): n = 0 for y in xrange(1,x+1): if x % y == 0: n = n + 1 if n == 2 : print x L1.append(x)print L1
The result is as follows:
2001120021200232002920047200512006320071200892010120107201132011720123201292014320147201492016120173….