Python Program for Legendre's Conjecture (original) (raw)

Last Updated : 31 Oct, 2025

Given a number n, the task is to verify Legendre’s Conjecture which states that there is always at least one prime number between the squares of two consecutive natural numbers n² and (n+1)². **For example:

Between 1² and 2² -> primes are 2, 3
Between 2² and 3² -> primes are 5, 7

Let’s explore different ways to verify this conjecture efficiently in Python.

Using sympy.primerange()

This method uses the primerange() function from the sympy library, which directly generates all prime numbers within a given range. It avoids writing any custom prime-checking logic and gives accurate results efficiently.

Python `

import sympy n = 10 primes = list(sympy.primerange(nn, (n+1)(n+1))) print("Primes in the range", nn, "and" ,(n+1)(n+1), "are:") for p in primes: print(p)

`

**Output

Primes in the range 100 and 121 are:
101
103
107
109
113

**Explanation:

Using sympy.isprime() with List Comprehension

This method checks each number between n² and (n+1)² using sympy.isprime() to verify primality. It is slightly slower than primerange() but still efficient and simple.

Python `

import sympy n = 10 primes = [i for i in range(nn, (n+1)(n+1)) if sympy.isprime(i)] print("Primes in the range", nn, "and", (n+1)(n+1), "are:") for p in primes: print(p)

`

**Output

Primes in the range 100 and 121 are:
101
103
107
109
113

**Explanation:

Using a Custom Prime Check

This method manually checks whether numbers between n² and (n+1)² are prime by dividing each number from 2 to its square root. It is slower than the previous methods but helps understand the concept behind prime verification.

Python `

import math n = 10 for i in range(nn, (n+1)(n+1)): if i > 1: for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: break else: print(i)

`

Output

101 103 107 109 113

**Explanation:

Using Sieve of Eratosthenes

This approach generates all prime numbers up to (n + 1)2 using the Sieve of Eratosthenes directly within the script, without defining a separate function. It’s ideal when verifying the conjecture for multiple values of n in a single run.

Python `

n = 10 lmt = (n + 1) * (n + 1) p = [True] * (lmt + 1) p[0] = p[1] = False

for i in range(2, int(lmt ** 0.5) + 1): if p[i]: for j in range(i * i, lmt + 1, i): p[j] = False

res = [i for i in range(n * n, lmt) if p[i]] for p in res: print(p)

`

Output

101 103 107 109 113

**Explanation:

Please refer complete article on Legendre's Conjecture for more details!