python如何判断一个数是否是素数
先来看下什么是python质数:
质数(Primenumber),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个因数的数)。
简单来说就是,只能除以1和自身的数(需要大于1)就是质数。举个栗子,5这个数,从2开始一直到4,都不能被它整除,只有1和它本身(5)才能被5整除,所以5就是一个典型的质数。
那么想计算出一个随机数是不是质数用Python应该怎么写呢?首先第一句话肯定是接受用户输入的数字:
n=int(input("pleaseenterthenumber:"))
接着要计算该数是不是质数,那么就要从2开始一直除到该数之前的那个自然数,很明显是一个数字范围:
foriinrange(2,n):
在循环体里面,每次循环当然就是要判断当次除法是否是整除,这里可以使用求模运算,也就是取余,当余数为0时,该数就不是质数:
ifn%i==0:
print("%disnotaprimenumber!"%n)
break
这个break意思就是当该数不是质数时,就跳出整个循环,该数就不是我们要的数字了。
那么,所有循环迭代都完成后还没有找出能整除的情况的话,那么可以判断该数就是一个质数,所以:
else:
print("%disaprimenumber!"%n)
那么此时,所有代码就写好了,不过为了看起来简单,没有罩一层是否大于1的判断,用户输入的数字默认需要大于1:
n=int(input("pleaseenterthenumber:"))
foriinrange(2,n):
ifn%i==0:
print("%disnotaprimenumber!"%n)
break
else:
print("%disaprimenumber!"%n)
这里要细细品味这段代码,else其实不是和if是一对,而是和for并排的,我们常见的是if…else…或者if…elif…else诸如此类,但其实for也可以和else搭配出现,在这段代码里,当某一次遍历结果余数为0后,break生效,那循环就结束了,那与之成对出现的else代码也就不执行了;当所有遍历结束后没有一次余数为0,那该循环就转到else开始执行,打印输出“该数为质数”。
以上内容为大家介绍了python培训之如何判断一个数是否是素数,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






