Latest web development tutorials

Python prime number judgment

Document Object Reference Examples Python3

A natural number greater than 1, except 1 and itself, but not by other natural numbers (a prime number) is divisible (2, 3, 5, 7, etc.), in other words the number except 1 and itself not have any other factor .


test.py file:

# - * - Coding: UTF- 8 - * - # Filename: test.py # Author by: www.w3big.com Digital # Python program for detecting user input is prime Users enter the number # num = int (input ( "Please enter a number:")) # Prime number greater than 1 if num> 1: # View factor for i in range (2, num): if (Num% i) == 0: print (num, " not prime") print (i, "multiplied", num // i, "is", num) break else: print (num, "is a prime number") # If the number entered is less than or equal to 1, is not prime else: print (num, "not prime")

Execute the above code output results:

$ python3 test.py 
请输入一个数字: 1
1 不是质数
$ python3 test.py 
请输入一个数字: 4
4 不是质数
2 乘于 2 是 4
$ python3 test.py 
请输入一个数字: 5
5 是质数

Document Object Reference Examples Python3