资讯内容
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 True2、单行程序扫描素数 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 False3、不使用模块的两种方法 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 TrueSHP少儿编程网-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
- 上一篇
python注释快捷键是什么
简介python注释快捷键:1、单行注释是【#】,Mac的快捷键是【command+/】,windows的快捷键是【Ctrl+/】;2、多行注释是三个单引号【'''注释'''】。本教程操作环境:windows7系统、python3.9版,DELLG3电脑。
- 下一篇
python区分大小写吗
简介python是区分大小写的,不管是变量、函数、还是类,都要严格的区分大小写。例如:page和Page是两个不同的变量,name和Name也是完全不同的两个变量。本教程操作环境:windows7系统、Python3版、DellG3电脑。python区分大小写吗?我们来通过示例来看看:如果能区分像m