How do you print 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.

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.

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.

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.

Here's a simple and intuitive version of checking whether it's a prime in a RECURSIVE function! :) (I did it as a homework assignment for an MIT class) In python it runs very fast until 1900. IF you try more than 1900, you'll get an interesting error :) (Would u like to check how many numbers your computer can manage?)

def is_prime(n, div=2):

    if div> n/2.0: return True

    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)

#The program:
until = 1000
for i in range(until):
    if is_prime(i):
        print i

Of course... if you like recursive functions, this small code can be upgraded with a dictionary to seriously increase its performance, and avoid that funny error. Here's a simple Level 1 upgrade with a MEMORY integration:

import datetime
def is_prime(n, div=2):
    global primelist
    if div> n/2.0: return True
    if div < primelist[0]:
        div = primelist[0]
        for x in primelist:
            if x ==0 or x==1: continue
            if n % x == 0:
                return False
    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)


now = datetime.datetime.now()
print 'time and date:',now
until = 100000
primelist=[]
for i in range(until):
    if is_prime(i):
        primelist.insert(0,i)
print "There are", len(primelist),"prime numbers, until", until
print primelist[0:100], "..."

finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"

Here are the resuls, where I printed the last 100 prime numbers found.

time and date: 2013-10-15 13:32:11.674448

There are 9594 prime numbers, until 100000

[99991, 99989, 99971, 99961, 99929, 99923, 99907, 99901, 99881, 99877, 99871, 99859, 99839, 99833, 99829, 99823, 99817, 99809, 99793, 99787, 99767, 99761, 99733, 99721, 99719, 99713, 99709, 99707, 99689, 99679, 99667, 99661, 99643, 99623, 99611, 99607, 99581, 99577, 99571, 99563, 99559, 99551, 99529, 99527, 99523, 99497, 99487, 99469, 99439, 99431, 99409, 99401, 99397, 99391, 99377, 99371, 99367, 99349, 99347, 99317, 99289, 99277, 99259, 99257, 99251, 99241, 99233, 99223, 99191, 99181, 99173, 99149, 99139, 99137, 99133, 99131, 99119, 99109, 99103, 99089, 99083, 99079, 99053, 99041, 99023, 99017, 99013, 98999, 98993, 98981, 98963, 98953, 98947, 98939, 98929, 98927, 98911, 98909, 98899, 98897] ...

It took your computer 0:00:40.871083 to calculate it

So It took 40 seconds for my i7 laptop to calculate it. :)

How do I print a prime number?

First, take the number N as input. Then use a for loop to iterate the numbers from 1 to N. Then check for each number to be a prime number. If it is a prime number, print it.

How do you print prime numbers from 1 to 100 in Python?

num1 = input("Input a number: ") num2 = input("Input another number: ") for x in range(num1,num2): prime = True for i in range(2,x): if (x%i==0): prime = False if prime == True: print x print "Done......" It classifies 1 as a Prime Number, which is incorrect.

Is there a prime number function in 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 print prime and composite numbers in Python?

Approach :.
Read input number using input() or raw_input() ..
Check if num is greater than 1..
Find factors. Run a for loop ranging from 2 to the num entered. ... .
If the number entered is either 0 or 1, we say that the number is neither prime nor composite number..
All other numbers are composite numbers..
Print the result..