极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

python质数如何判断

极客小将2021-03-14-
简介python质数判断的方法:首先运用python的数学函数;然后单行程序扫描素数,代码为【[pforpinrange(2,N)if0notin[p%dfordinrange(2,int(sqrt(p)】。本教程操作环境:windows7系统、python3.9版,DELLG3电脑。python质数判

python质数判断的方法:首先运用python的数学函数;然后单行程序扫描素数,代码为【[ p for p in range(2, N) if 0 not in [ p% d for d in range(2,int(sqrt(p)】。SHP少儿编程网-https://www.pxcodes.com

SHP少儿编程网-https://www.pxcodes.com

本教程操作环境:windows7系统、python3.9版,DELL G3电脑。SHP少儿编程网-https://www.pxcodes.com

python质数判断的方法:SHP少儿编程网-https://www.pxcodes.com

1、运用python的数学函数 SHP少儿编程网-https://www.pxcodes.com

import math def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True

2、单行程序扫描素数 SHP少儿编程网-https://www.pxcodes.com

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模块 SHP少儿编程网-https://www.pxcodes.com

from itertools import count def isPrime(n): www.jb51.net if n <= 1: return False for i in count(2): if i * i > n: return True if n % i == 0: return False

3、不使用模块的两种方法 SHP少儿编程网-https://www.pxcodes.com

方法1:SHP少儿编程网-https://www.pxcodes.com

def isPrime(n): if n <= 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True

方法2:SHP少儿编程网-https://www.pxcodes.com

def isPrime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True

SHP少儿编程网-https://www.pxcodes.com

eg:求出20001到40001之间的质数(素数)SHP少儿编程网-https://www.pxcodes.com

既然只能被1或者自己整出,那说明只有2次余数为0的时候,代码如下:SHP少儿编程网-https://www.pxcodes.com

#!/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

结果如下:SHP少儿编程网-https://www.pxcodes.com

20011 20021 20023 20029 20047 20051 20063 20071 20089 20101 20107 20113 20117 20123 20129 20143 20147 20149 20161 20173 ….

相关免费学习推荐:python视频教程SHP少儿编程网-https://www.pxcodes.com

以上就是python质数如何判断的详细内容,更多请关注少儿编程网其它相关文章!SHP少儿编程网-https://www.pxcodes.com

网友点评

共有5条评论来说两句吧...

在线客服