Monday 5 January 2015

Prime number check in python


Question:
a) Write a simple program to find whether the number is prime or not. Check whether 10 is prime or not.
b) Write a function in python to find the whether a number is prime not. Return True if prime and False if not. Check whether 10 is prime or not.
c) Write a program in python which takes a number input from the user and returns if the number is prime or not. Check whether 10 is prime or not.

Answer: I have commented the code please do ask if you have any doubt. If you feel that you have a better solution than this then please do send it to me.
a) 
n = 10 #variable declaration
if n>1:#tO check if the number is greater than 1
 for i in range(2,n):
 #Loop less than the number
 #Loop excluding the number and greater than 1
  if n%i == 0:#Loop to check the divisibility by any numbers
   print "The number is not a prime number" #Printing the output
   break
 
  print "The number is a prime number" #Printing the output 

Output:

The number is not a prime number

b)

def is_prime(n):#Function declaration
 if n>1:#tO check if the number is greater than 1
  for i in range(2,n):
  #Loop less than the number
  #Loop excluding the number and greater than 1
   if n%i == 0:#Loop to check the divisibility by any numbers
    return False #To return False
  
   return True #To return True 

is_prime(10)

Output:

False

c)

def is_prime(n):#Function declaration
 if n>1:#tO check if the number is greater than 1
  for i in range(2,n):
  #Loop less than the number
  #Loop excluding the number and greater than 1
   if n%i == 0:#Loop to check the divisibility by any numbers
    return False #To return False
  
   return True #To return True 

x = int(raw_input("Enter the number to check"))#INterger input from the user
is_prime(x)

Output:

>>> Enter the number to check
...10
>>>False

Copyright: I haven't copied above from anywhere. This is my original work.

No comments:

Post a Comment