English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Example of checking if an integer is a prime number using for loop and if ... else statement. If the number is not a prime number, it will be explained why it is not a prime number in the output.
To understand this example, you should understand the followingPython programmingTopic:
greater than1are positive integers, except1and there are no other factors outside, and the number itself is called a prime number.2,3,5,7are prime numbers because they have no other factors.6is not a prime number (it is composite) because2 x 3 = 6.
# Program checks if a number is a prime number num = 407 # Get input from the user #num = int(input("Enter a number: ")) # Prime numbers are greater than1 if num > 1: # Check character for i in range(2): if (num % i) == 0: print(num, "is not a prime number") print(i, "multiplied by", num//(i, "equals", num) break else: print(num, "is a prime number") # If the input number is less than # or equal to1It is not a prime number else: print(num, "is not a prime number")
Output result
407 is not a prime number 11multiplied by37equals407
In this program, we will check if the variable num is a prime number. Less than or equal to1The number is not a prime number. Therefore, we only check num greater than1to be performed.
We check if num can be2to num-1divisible by any number. If we find a factor in the range, then the number is not a prime number. Otherwise, the number is a prime number.
We can narrow down the range of numbers to find factors.
In the above program, our search range is2to num - 1.
We can use the range[2,num/2]]2,num ** 0.5]. The next range is based on the fact that composite numbers must have factors less than the square root of the number. Otherwise, the number is a prime number.
You can change the value of the variable num in the source code above to check if the number is a prime number of other integers.