python中如何编程求1到100之间的素数
1、新建python文侍蔽件,testprimenum.py;
2、编写python代码,求1到100之间的素数;
list1 = []
i = 2
for i in 卜谈源range(2,101):
j = 2
型态 for j in range (2,i):
if i%j == 0:
break
else:
list1.append(i)
print(list1)
3、窗口中右击,选择‘在终端中运行Python文件’;
4、查看执行结果,1-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]
#!/usr/bin/python
#-*- coding:UTF-8 -*-
#求游逗素神薯卖数
list=[]
i=2
for i in range (2,100):
j=2
for j in range(2,i):
if(i%j==0):
break
else:
list.append(i)
print(list)
扩展资料:
python:for语手拍句的使用方法
for循环的语法格式:
for i in range(n):#从数据类型中拿一个值赋值给i
print(i)#打印i
例如:
#for
for i in range (1,6,2):#从一开始到六之前每隔上2个数字
print(i)#结果为1,3,5
# ------------------------------------------------
s = ["man", "woman", "girl", "boy", "sister"]
for i in s:#列表s中的每个元素给i
print(i)
#-------------------------------------------------
for i in range(5):
print(i)#结果为:0,1,2,3,4
for循环实例:数字0,1,2组成一个百位数,并且数字不重复!
#for
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if (i != 0) and (i != j) and (i != k) and (j != k):
print (i,j,k)
def primes(x):
# prepair data space
庆昌 plist = [0, 0] + range(2,x+1)
for i in xrange(2, x):
if plist[i]:
闹和 plist[i+i::i] = [0] * len(plist[i+i::i])
return filter(None, plist)
print primes(100)
筛选法是高效的素数列表计算算法, python的列表切液差盯片赋值可以极大地简化代码
result=[]
for i in range(2,101):
纤升 for j in range(2,i):
if i%j==0
毕肆 break
else:
手竖轿 result.append(i)
print(result)
广告 您可能关注的内容 |