interview questions

Find prime numbers in given range

Hello

In this article, we are going to see how to print all prime numbers between a given range. We have shared code in python language.

What is Prime number?

Prime number is a number who is divisible by 1 and that number only. There are no factors other than these 2 two.

Example of Prime number: 11,13,29 . All of these numbers do not have factors other than 1 and given number. Prime number can only be odd number.

How to find whether a number is prime or not?

For a given number, we will check whether a number do not have factor from 2 till square root of the number. We will run a iterative loop and see if there is any number which is factor of that number.

How to check whether a number is prime through programming

 

import math
def checkPrime(number):
	if(number<1):
		return False

	i=2
	while(i<math.sqrt(number)):
		if(number%i==0):
			return False
			break
		i+=1

	return True

def getPrimeNumberinRange(number1, number2):
	if(number1>number2):
		return "Invalid range"
	primenumberlist= []
	j=number1
	while(j<number2+1):
		if(checkPrime(j)):
			primenumberlist.append(j)
		j+=1
	return primenumberlist

print(getPrimeNumberinRange(1000,3000))

In this article, we have saw how to print prime number in a given range in Python. If you have any confusion regarding the code, please do comment in discussion thread below or send us email to info@xamnation.com. 

You can use our code in your website. Kindly do acknowledge us by linking our website or this page. 

About Xamnation

If you are interested, you can reach us at info@xamnation.com for more details. 

Leave a Comment

Your email address will not be published.