Find all the primes of the Python implementation

Source: Internet
Author: User

Find all the primes of the Python implementation

Finding prime numbers is also a simple topic in learning python. The knowledge points involved are: the application of Python's built-in function filter ().

Ideas are as follows:

  • In all natural numbers, first take the Prime 2 and then filter out all numbers with a factor of 2 (because these numbers are not primes) to get a new sequence
  • Then take the prime number 3 in the new sequence and filter out all numbers with a factor of 3 to get a new sequence
  • The first number is then removed in the new sequence, and all the numbers that are the factor are filtered out.
  • Follow the steps above to take out all the numbers

The implementation code is as follows:

#coding =utf-8#寻找所有的素数 def not_div(n):    return Lambdax:x%n!=0 def pro_odd():#从3开始的奇数生成器n=1     while True: n=n+2        yieldN def primes():#定义一个生成器, returning the next prime number continuously    yield 2It=pro_odd () while True: N=next (IT)yieldN It=filter (Not_div (n), it)#测试 forIinchPrimes ():#由于是无穷序列, there is a limit to the output below    if(i< -): Print (i)Else: Break   

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Find all the primes of the Python implementation

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.