Python程序检查数字是否为素数
在此,我们将编写一个程序来测试给定的大于1的数字是否为质数。
质数是一个大于1的正整数,它只有两个因数1和数字本身,例如数字:2,3、5、7…等是质数,因为它们只有两个因数。即1和数本身。
# Python program to check if the input number is prime or not #Take input from the user num = int(input("Please enter the number: ")) #Check if the given number is greater than 1 if num > 1: # Iterate through 2 to num/2. for i in range(2,num//2): #Select if the number is divisible by any number between 2 and num/2. if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: #If given number is not fully divisible by any number between 1 and num/2, then its prime. print(num,"is a prime number") # Also, if the number is less than 1, its also not a prime number. else: print(num,"is not a prime number")
输出结果
Please enter the number: 47 47 is a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: -2 -2 is not a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: 3333 3333 is not a prime number 3 times 1111 is 3333
用户输入1:数字:47
输出:Number(47)是质数
用户输入2:num=-2
输出:Number(-2)不是质数
用户输入3:num=3333
输出:Number(3333)不是素数
在上面的程序中,我们检查用户输入的数字是否为素数。由于小于或等于1的数字不是质数,因此我们仅考虑大于1的用户输入。
然后,我们检查用户输入是否可以被2到用户输入/2之间的任意数完全整除。如果我们在该范围内找到一个因数,则该数字不是质数,而是质数。