菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python - 获取 100 以内的质数

Python 100例 Python 100例

题目: 获取 100 以内的质数。

程序分析:质数(prime number)又称素数,有无限个。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数称为质数,如:2、3、5、7、11、13、17、19。

方法一:

#!/usr/bin/python# -*- coding: UTF-8 -*-num=[]; i=2foriinrange(2,100): j=2forjinrange(2,i): if(i%j==0): breakelse: num.append(i)print(num)

方法二:

importmathdeffunc_get_prime(n): returnfilter(lambdax: not[x%iforiinrange(2, int(math.sqrt(x))+1)ifx%i ==0], range(2,n+1))printfunc_get_prime(100)

输出结果为:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Python 100例 Python 100例

AI 思考中...

4 篇笔记 写笔记

  1. #0

    张小川

    835***[email protected]

    1

    参考方法:

    import math
    N = 100 
    print [ p for p in range(2, N) if 0 not in [ p%i for i in range(2,int(math.sqrt(p))+1)]] 
    

    张小川

    835***[email protected]

    9年前 (2017年08月20日)
  2. #0

    红烧土豆块

    545***[email protected]

    8

    参考:

    [n for n in range(1,100) if not [m for m in range(2,n) if n % m ==0]]

    红烧土豆块

    545***[email protected]

    9年前 (2017年11月28日)
  3. #0

    阳光不锈

    173***[email protected]

    3

    Python3 采用递归:

    #递归函数求质数
    def prime(n):
     if n==2:
     print(n)
     return
     else:
     for i in range(2,n):
     if n%i==0:
     break
     else:
     print(n,end=',')
     prime(n-1)
    #获取 100 以内的质数
    prime(100)

    阳光不锈

    173***[email protected]

    8年前 (2018年02月18日)
  4. #0

    newpy

    bin***@163.com

    4

    filter 方法,匿名函数,如果推导式为空,则返回值为 True。为便于代码理解,省略了求平方根。

    文章示例中方法二的写法可以优化如下:推导式中将 x % i 修改为 x

    Type "help", "copyright", "credits" or "license" for more information.>>> lis = list(filter(lambda x: not[x for i in range(2, x) if x % i == 0], range(2, 100)))>>> print(lis) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

    newpy

    bin***@163.com

    8年前 (2018年08月06日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /