This article mainly introduces Python's example of how to efficiently solve the prime number code. This article provides code examples directly. if you need a friend, you can refer to the prime number, which is 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