当前位置: 首页 > 图灵资讯 > 行业资讯> 如何用python打印100以内的质数?

如何用python打印100以内的质数?

来源:图灵python
时间: 2024-10-09 17:58:28

在计算机使用的过程中,计算是必不可少的。编程中含有大量的数学计算,可以帮助我们解决实际难操作的问题。有的时候我们会忘记质数是什么,之前小编向大家介绍过在python中判断质数的方法(判断数字是否为质数的方法,那你知道如何在python中打印100以内的质数吗?本文小编将向大家演示用python打印100以内的质数的过程。

代码:

#1000以内素数

importmath
defis_prime(n):

ifn==1:
returnFalse
foriinrange(2,int(math.sqrt(n))+1):
ifn%i==0:
returnFalse
else:
returnTrue

count=0
number=[]
foriinrange(0,1000,1):
ifis_prime(i):
number.append(i)
count+=1
print('{}:{}'.format(count,i))#碰到的新语句,可删除

print(number)

输出:

>
[0,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,101,103,107,109,
113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241
,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,
389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,
541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,
677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,
839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]

这个方法很容易理解,如果有要打印100以内质数的或者要打印其他数字以内的质数,可以用上述代码哦~还是很方便的。