Python 程序检查数字是否为素数
一个素数是一个大于 1 的自然数,它不是两个较小自然数的乘积。任何大于 1 且只有两个因数(即 1 和它本身)的整数都称为素数。
假设我们的输入如下所示:
7
输出应如下所示:
Prime Number
检查数字是否为素数
让我们使用for 循环检查一个数字是否为素数:
示例
# Number to be checked for prime n = 5 # Check if the number is greater than 1 if n > 1: for i in range(2, int(n/2)+1): if (n % i) == 0: print(num, "is not a prime number") break else: print(n, "is a prime number") # If the number is less than 1, its also not a prime number. else: print(n, "is not a prime number")
输出
5 is a prime number
使用 sqrt() 检查数字是否为素数
让我们使用sqrt() 方法检查一个数字是否为素数:
示例
from math import sqrt # Number to be checked for prime n = 9 flag = 0 if(n > 1): for k in range(2, int(sqrt(n)) + 1): if (n % k == 0): flag = 1 break if (flag == 0): print(n," is a Prime Number!") else: print(n," is Not a Prime Number!") else: print(n," is Not a Prime Number!")
输出
9 is Not a Prime Number!
广告