Python enables efficient solution of prime code instances

Source: Internet
Author: User
Prime numbers are often needed in programming.

As an example of learning Python, here is a program that efficiently solves a range of primes without using division or modulo operations.

#coding: Utf-8    #设置python文件的编码为utf-8, so you can write Chinese note def primerange (n):  myarray=[1 for x in range (n+1)] # #列表解析, Generate a list of length (n+1) with each value 1  myarray[0]=0  myarray[1]=0 startpos=2 while  startpos <= N:    if myarray[ Startpos]==1:      key=2      resultpos = startpos * Key #可知startPos的整数倍都不是素数, set the integer multiples of startpos to 0 for non-prime while      Resultpos <= N:        myarray[resultpos] =0        key + = 1        resultpos = startpos *key    startpos + = 1  Resultlist=[]  # #将最终的素数保存在resultList列表返回  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:  PrimeR Esult=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.