Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to get the nth prime number using SymPy in Python

abhilash

What is SymPy?

SymPy is a library for symbolic mathematics in Python.

We use pip to install SymPy with the following command:

pip install sympy

The prime method

The prime method gets the nth prime number, starting with 2 as the first prime number. n must be a positive integer exclusive of zero (0), or else the method throws a ValueError.

Syntax

sympy.prime(n)

Parameters

  • n: It is the prime number that should be greater than 0.

Return value

The method returns the nth prime number.

Code

from sympy import prime

n = 5

print("prime(%s) = %s" % (n, prime(n)))

Code explanation

  • Line 1: We import the prime function from the SymPy package.
  • Line 3: We define n.
  • Line 5: We get the nth prime number using the prime(n) function.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring