# Python Prime Number Coding Question and Solutions

### Check whether a number is Prime or Not Python Program

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, ….}.

This Python program checks whether a given number is a prime number or not. A prime number is a perfect natural number that can only be divisible by itself and by 1. This Python program checks the factors using the for loop and conditional statement and prints the desired output.

```#Variable definition and assignment
inputn = 3

#Taking user input
#inputn = int(input("Enter a number: "))

if inputn > 1:
# check for factors
for i in range(2,inputn):
if (inputn % i) == 0:
print(inputn,"is not a prime number.")
# print(i,"times",inputn//i,"is",inputn) - try if intrested times output
break
else:
print(inputn,"is a prime number.")

#If the input number is less than or equal to 1, then it is not prime
else:
print(inputn,"is not a prime number.")```

Output

3 is a prime number.

In this article, we have extensively discussed what Prime number in Python is and how to identify it. We hope that this blog has helped you enhance your knowledge regarding Python and if you would like to learn more, check out our articles. Do upvote our blog to help other ninjas grow. Happy Coding!”

### Easy Method

1. Iterative Solution - In this method we’ll use simple if-else statements and for loop to iterate though all the number in a given range while checking for factors of the number.

For a given integer input we check,

• If the number is greater than 2.
• If the number has any factors in the range [2,number].
• If any off the above conditions are satisfied, the number isn’t a Prime.

```num = 8
flag = 0
for i in range(2,num):
if num%i==0:
flag = 1
break
if flag == 1:
print('Not Prime')
else:
print("Prime")```

Output

Not Prime

2. Break Condition

```num = 8
flag = 0
if num<2:
flag = 1
else:
for i in range(2,num):
if num%i==0:
flag = 1
break

if flag == 1:
print('Not Prime')
else:
print("Prime")```

Output

Not Prime

3. Optimization by n/2 iterations

```num = 15
flag = 0
if num<2:
flag = 1
else:
for i in range(2,int((num/2)+1)):
if num%i==0:
flag = 1
break

if flag == 1:
print('Not Prime')
else:
print("Prime")```

Output

Not Prime

4. Optimization by √n

```num = 7
flag = 0
if num<2:
flag = 1
else:
for i in range(2,int(pow(num,0.5)+1)):
if num%i==0:
flag = 1
break

if flag == 1:
print('Not Prime')
else:
print("Prime")```

Output

Not Prime

5. Optimization by skipping even iteration

```num = 15
flag = 0
if num<2:
flag = 1
elif num == 2:
flag = 0
else:
for i in range(3,int(pow(num,0.5)+1),2):
if num%i==0:
flag = 1
break

if flag == 1:
print('Not Prime')
else:
print("Prime")```

Output

Not Prime

6. Basic Recursion technique

```num = 15
def checkPrime(num,iter=2):
if num == iter:
return True
if num%iter==0:
return False
if num<2:
return False
return checkPrime(num,iter+1)
if checkPrime(num)==True:
print("Prime")
else:
print("Not Prime")```

Output

Not Prime

### Method 1

Using For Loop

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.

```num = 2
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, int(num/2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
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

2 is a prime number

### Method 2

Now let’s see the code for the first optimization method ( i.e. checking till √n )

```from math import sqrt
# n is the number to be check whether it is prime or not
n = 1

# this flag maintains status whether the n is prime or not
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

True

### Method 3

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 number11 times 37 is 407

### Method 4

Using Lambda Function Print Prime Number or Not

```isprime = lambda x: int(x) > 0 and (x == 2 or x == 3 or [x % i == 0 for i in range(2,int(x**0.5)+1)].count(True) == 0)

print(isprime(-7))
print(isprime(7))```

Output

False True

### Method 5

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")```

### Method 6

Print Only Prime Number From 0 to User Defined Numbers, Using def Function in Python

```def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True

def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes

num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)```

Output

Enter upper limit: 100[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Explanation

The first one is the is_prime that you have seen before. Now we created another function named all_primes. In the all_primes function, we create a list named primes to hold the prime numbers. Then run a for loop using range. The range starts at 2 and runs until num+1 so that it goes until num. We are starting at 2. Because 2 is the first prime number. Inside the loop, call the is_prime function and check the return. If the return is True then append the n in the primes list. Then return the primes list.

That’s it.

### Method 7

Short Python Code to check Number is Prime or not, (Will only check from range 2 to n)

```a=int(input("Enter number: "))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime")```

Output

Enter number: 7Number is prime

### Program Explanation

1. User must enter the number to be checked and store it in a different variable.

2. The count variable is first initialized to 0.

3. The for loop ranges from 2 to the half of the number so 1 and the number itself aren’t counted as divisors.

4. The if statement then checks for the divisors of the number if the remainder is equal to 0.

5. The count variable counts the number of divisors and if the count is lesser or equal to 0, the number is a prime number.

6. If the count is greater than 0, the number isn’t prime.

7. The final result is printed.

### Method 8

Write a Python function that takes a number as a parameter and check the number is prime or not.

Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.

```def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))```

Output

False

### Method

Previous Post Next Post