Python-Python tutorial

Source: Internet
Author: User
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

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: info-contact@alibabacloud.com 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.