    # Hướng dẫn prime number in python

Example to check whether an integer is a prime number or not using for loop and if...else statement. If the number is not prime, it's explained in output why it is not a prime number.

Nội dung chính

• Example 1: Using a flag variable
• Example 2: Using a for...else statement
• Source Code
• What is the Prime number
• Prime Number Program in Python
• Method 1:
• Method 2: Fastest Algorithm to Find Prime Numbers
• What is a prime number in Python?
• What is prime number explain with example?
• Is prime number function Python?
• How do you show prime numbers in Python?

To understand this example, you should have the knowledge of the following Python programming topics:

• Python if...else Statement
• Python for Loop
• Python break and continue

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, `2 x 3 = 6`.

## Example 1: Using a flag variable

``````# Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable
flag = False

# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")``````

In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from `2` to `num - 1`. If we find a factor in that range, the number is not prime, so we set flag to `True` and break out of the loop.

Outside the loop, we check if `flag` is `True` or `False`.

• If it is `True`, `num` is not a prime number.
• If it is `False`, `num` is a prime number.

Note: We can improve our program by decreasing the range of numbers where we look for factors.

In the above program, our search range is from 2 to `num - 1`.

We could have used the range, `range(2,num//2)` or `range(2,math.floor(math.sqrt(num)+1))`. The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.

You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.

In Python, we can also use the `for...else` statement to do this task without using an additional `flag` variable.

## Example 2: Using a for...else statement

``````# Program to check if a number is prime or not

num = 407

# To take input from the user
#num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")``````

Output

```407 is not a prime number
11 times 37 is 407```

Here, we have used a `for..else` statement to check if `num` is prime.

It works on the logic that the `else` clause of the `for` loop runs if and only if we don't break out the `for` loop. That condition is met only when no factors are found, which means that the given number is prime.

So, in the `else` clause, we print that the number is prime.

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.

2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, `2 x 3 = 6`.

## Source Code

``````# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)``````

Output

```Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
```

Here, we store the interval as lower for lower interval and upper for upper interval, and find prime numbers in that range. Visit this page to learn how to check whether a number is prime or not.

View Discussion

Improve Article

Save Article

• Discuss
• View Discussion

Improve Article

Save Article

Given a positive integer N, The task is to write a Python program to check if the number is Prime or not in Python.

Examples:

```Input:  n = 11
Output: True

Input:  n = 1
Output: False```

## What is the Prime number

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.

### Method 1:

The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.

## Python3

`num ``=` `11`

`if` `num > ``1``:`

`    ``for` `i ``in` `range``(``2``, ``int``(num``/``2``)``+``1``):`

`        ``if` `(num ``%` `i) ``=``=` `0``:`

`            ``print``(num, ``"is not a prime number"``)`

`            ``break`

`    ``else``:`

`        ``print``(num, ``"is a prime number"``)`

`else``:`

`    ``print``(num, ``"is not a prime number"``)`

Output

`11 is a prime number`

### Method 2: Fastest Algorithm to Find Prime Numbers

Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked. Now let’s see the code for the first optimization method ( i.e. checking till √n )

## Python3

`from` `math ``import` `sqrt`

`n ``=` `1`

`prime_flag ``=` `0`

`if``(n > ``1``):`

`    ``for` `i ``in` `range``(``2``, ``int``(sqrt(n)) ``+` `1``):`

`        ``if` `(n ``%` `i ``=``=` `0``):`

`            ``prime_flag ``=` `1`

`            ``break`

`    ``if` `(prime_flag ``=``=` `0``):`

`        ``print``(``"True"``)`

`    ``else``:`

`        ``print``(``"False"``)`

`else``:`

`    ``print``(``"False"``)`

Output:

`False`

RECOMMENDED ARTICLE – Analysis of Different Methods to find Prime Number in Python

### What is a prime number in Python?

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6 .

### What is prime number explain with example?

The numbers which have only two factors, i.e. 1 and the number itself are called prime numbers. In other words, prime numbers are divisible by only 1 and the number itself. That means they are not divisible by any other numbers. Some examples of prime numbers are 7, 11, 13, 17,…

### Is prime number function Python?

Python Function to Check for Prime Number The above function is_prime() takes in a positive integer n as the argument. If you find a factor in the specified range of (2, n-1), the function returns False —as the number is not prime. And it returns True if you traverse the entire loop without finding a factor.

### How do you show prime numbers in Python?

Python Program to Display Prime Numbers in a Given Range.

min = int(input("Enter the min : ")).

max = int(input("Enter the max : ")).

for n in range(min,max + 1):.

if n > 1:.

for i in range(2,n):.

if (n % i) == 0:.

break.. 