zoukankan      html  css  js  c++  java
  • 5、用filter求素数

    计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:

    首先,列出从2开始的所有自然数,构造一个序列:

    2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

    取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:

    3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

    取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

    5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

    取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

    7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

    不断筛下去,就可以得到所有的素数。

    # -*- coding: utf-8 -*-
    
    #构造一个从3开始的奇数序列
    def _odd_iter():
        n = 1
        while True:
            n = n + 2
            yield n
    
    #定义一个筛选函数
    def _not_divisible(n):
        return lambda x: x % n > 0
    
    #定义一个生成器,不断返回下一个素数
    def primes():
        yield 2
        it = _odd_iter() # 初始序列
        while True:
            n = next(it) # 返回序列的第一个数
            yield n
            it = filter(_not_divisible(n), it)  # 构造新序列
    
    # 打印100以内的素数:
    for n in primes():
        if n < 100:
            print(n)
        else:
            break
    

      

  • 相关阅读:
    Abp Swagger API中文说明配置方法
    ABP框架中使用MySQL数据库
    windows + jenkins + .net core + iis自动化部署新手入门
    在图片上画矩形框
    base64转换成np、opencv、PIL
    RankSVM
    tf.placeholde函数解释与用法
    slim.arg_scope()的使用
    SSD网络结构
    tensorflow学习笔记
  • 原文地址:https://www.cnblogs.com/zwb8848happy/p/8427994.html
Copyright © 2011-2022 走看看