Python implements efficient prime number code examples, python Prime Number
Prime numbers are frequently used in programming.
As an example of learning Python, the following is a program that efficiently solves prime numbers within a range. Division or modulo operations are not required.
# Coding: UTF-8 # Set the python file encoding to UTF-8, so that you can write the Chinese comment def primeRange (n): myArray = [1 for x in range (n + 1)] # list parsing: generate a list with a length of (n + 1, each value is 1 myArray [0] = 0 myArray [1] = 0 startPos = 2 while startPos <= n: if myArray [startPos] = 1: key = 2 resultPos = startPos * key # it can be seen that the integer multiples of startPos are not prime numbers. The position of the integer multiples of startPos is set to 0 to indicate non-prime numbers while resultPos <= n: myArray [resultPos] = 0 key + = 1 resultPos = startPos * key startPos + = 1 resultList = [] # Save the final prime number in the resultList list and return startPos = 0 while startPos <= n: if myArray [startPos] = 1: resultList. append (startPos) startPos + = 1 return resultListnumString = raw_input ("Input the Range (> 3):") numInt = int (numString) if numInt <= 3: print "The Number Need to be greater than 3" else: primeResult = primeRange (numInt) print "The Result is:", primeResult