Prime number (Prime number), also known as prime number, refers to the number of natural numbers greater than 1, except 1 and the number itself, that cannot be divisible by other natural numbers (it can also be defined as a number with only two factors: 1 and the number itself) .
So what should I write in Python if I want to calculate whether a random number is a prime number? First of all, the first sentence must be the number entered by the user:
n =int(input("please enter the number:"))
Next, to calculate whether the number is a prime number, then you have to divide from 2 to the natural number before the number, which is obviously a range of numbers:
for i inrange(2, n):
In the loop body, of course, each loop is to determine whether the current division is an aliquot. Here, you can use modulo operation, that is, take the remainder. When the remainder is 0, the number is not a prime number:
if n % i ==0:print("%d is not a prime number!"% n)break
This break means that when the number is not a prime number, it jumps out of the entire loop, and the number is not the number we want.
Then, after all loop iterations are completed, if the divisible condition is not found, then it can be judged that the number is a prime number, so:
else:print("%d is a prime number!"% n)
At this time, all the code is written, but for the sake of simplicity, there is no judgment whether the cover layer is greater than 1, and the number entered by the user needs to be greater than 1 by default:
n =int(input("please enter the number:"))for i inrange(2, n):if n % i ==0:print(" %d is not a prime number!"% n)breakelse:print(" %d is a prime number!"% n)
Content expansion:
Examples of prime number judgment:
for i inrange(2,100):for j inrange(2,i):if i%j==0:breakelse:print(i,end='\t')
Recommended Posts