Prime functions in Python SymPy

How to get prime numbers quickly in python using library functions ?

Library functions always makes our code easy so here we are going to discuss some library function in python to work upon prime numbers. SymPy is a python module which contains some really cool prime number related library functions. Given below is the list of these functions :

 

  1. isprime(n) : It tests if n is a prime number (True) or not (False).
  2. primerange(a, b) : It generates a list of all prime numbers in the range [a, b).
  3. randprime(a, b) : It returns a random prime number in the range [a, b).
  4. primepi(n) : It returns the number of prime numbers less than or equal to n.
  5. prime(nth) : It returns the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
  6. prevprime(n) : It returns the prev prime smaller than n.
  7. nextprime(n) : It returns the next greater prime than n.
  8. sieve.primerange(a, b) : It generates all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes.
# Library functions for prime
import sympy
# Output : True
print sympy.isprime(5)                       
# Output : [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]
print list(sympy.primerange(0, 100))     
    
print sympy.randprime(0, 100# Output : 83
print sympy.randprime(0, 100# Output : 41
print sympy.prime(3)           # Output : 5
print sympy.prevprime(50)      # Output : 47
print sympy.nextprime(50)      # Output : 53
# Output : [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]
print list(sympy.sieve.primerange(0, 100))

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar