PHP前端开发

python质数如何判断

百变鹏仔 1个月前 (01-22) #Python
文章标签 质数
python质数判断的方法:首先运用python的数学函数;然后单行程序扫描素数,代码为【[ p for p in  range(2, N) if 0 not in [ p% d for d in range(2,int(sqrt(p)】。

本教程操作环境:windows7系统、python3.9版,DELL G3电脑。

python质数判断的方法:

1、运用python的数学函数 

import math  def isPrime(n):   if n <p><strong>2、单行程序扫描素数 </strong></p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><pre class="brush:php;toolbar:false">from math import sqrt N = 100[ p for p in  range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]

运用python的itertools模块 

from itertools import count def isPrime(n): www.jb51.net  if n  n:       return True    if n % i == 0:       return False

3、不使用模块的两种方法 

方法1:

def isPrime(n):   if n <p>方法2:</p><pre class="brush:php;toolbar:false">def isPrime(n):   if n <p>   </p><p>eg:求出20001到40001之间的质数(素数)</p><p>既然只能被1或者自己整出,那说明只有2次余数为0的时候,代码如下:</p><pre class="brush:php;toolbar:false">#!/usr/bin/python L1=[]for x in xrange(20001,40001): n = 0 for y in xrange(1,x+1): if x % y == 0:  n = n + 1 if n == 2 : print x L1.append(x)print L1

结果如下:

2001120021200232002920047200512006320071200892010120107201132011720123201292014320147201492016120173….

相关免费学习推荐:python视频教程