Python实现输出某区间范围内全部素数的方法
作者:Guo_Apple 时间:2022-04-25 10:04:50
本文实例讲述了Python实现输出某区间范围内全部素数的方法。分享给大家供大家参考,具体如下:
# -*- coding: utf-8 -*-
# 简述:区间范围101-200
# 要求:判断这个区间内有多少个素数,并逐一输出。
def prime(m,n):
list1=[]
list2=[]
for i in range(m,n+1):
list1.append(i)
for j in range(2,m/2):
if i%j==0:
list2.append(i)
break
#print list(set(list1).difference(set(list2)))#list1中有而list2中没有的
list=[i for i in list1 if i not in list2]
list.sort()
print list
print "该区间共有素数%d个"%len(list)
if __name__=="__main__":
print "脚本之家测试结果:"
m=int(raw_input("请输入区间左端点:"))
n=int(raw_input("请输入区间右端点:"))
prime(m,n)
运行结果:
脚本之家测试结果:
请输入区间左端点:101
请输入区间右端点:200
[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
该区间共有素数21个
运行效果截图:
总结:
1、#注释掉的一行也是可以出结果的,但是list中的元素没有排序,用了sort()
也是不行,列表补集这部分的知识需要补充
2、判断非素数我用了比较笨的方法,先算出素数再算补集,是因为直接判断素数无法运行出结果,汗
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/Guo_Apple/article/details/68941990
标签:Python,素数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
垂直无缝滚动图片(兼容性好)实例教程源码下载
2010-04-06 12:16:00
![](https://img.aspxhome.com/file/UploadPic/20104/6/scrollnews-65s.jpg)
python重要函数eval多种用法解析
2023-02-08 20:16:46
Python程序慢的重要原因
2023-10-08 16:17:40
asp全面解析Server对象
2008-10-19 17:24:00
Adobe AIR beta 2震撼发布!
2007-10-07 11:57:00
PHP中单引号和双引号的区别详解
2023-05-25 08:16:51
Windows XP操作系统下的MYSQL安装过程
2008-11-24 12:52:00
Web表单设计:表单结构
2011-04-22 12:32:00
ASP错误大全
2009-05-26 15:45:00
getElementsByAttribute
2009-10-27 12:13:00
深入浅出MySQL双向复制技术
2009-03-25 15:40:00
MySQL也能并发导入数据
2010-03-25 10:38:00
Python TypeError: ‘float‘ object is not subscriptable错误解决
2023-09-13 05:33:02
![](https://img.aspxhome.com/file/2023/9/62249_0s.png)
sql ntext数据类型字符替换实现代码
2011-09-30 11:08:00
2007流行网站导航设计欣赏
2008-02-18 12:20:00
![](https://img.aspxhome.com/file/UploadPic/20082/18/2008218122731730s.jpg)
python实现发送和获取手机短信验证码
2023-08-09 08:02:26
Python os.access()用法实例
2022-12-06 01:37:50
[翻译]标记语言和样式手册 Chapter 10 应用CSS
2008-02-02 18:44:00
![](https://img.aspxhome.com/file/UploadPic/20082/2/200822192227241s.jpg)
BootStrap创建响应式导航条实例代码
2023-08-09 02:09:55
![](https://img.aspxhome.com/file/2023/4/56054_0s.gif)
什么样的图标更具有可用性
2007-10-16 17:47:00
![](https://img.aspxhome.com/file/UploadPic/200710/16/20071016174919899s.jpg)