Home > Python > Basic Python Programs

Ch. 3.3 Finding Prime Number Greater or Lesser Than a Given Value

Chapters Index
Program 1

Finding Prime Number Greater or Lesser Than a Given Value

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.

Mathematical Problem Formulation

Input

Given number (e.g., 53).

Call next_prime(given_value)

Increment num by 1.

Check if num is Prime:

Start loop: Check divisibility from 2 to num - 1.

  • If num is divisible by any i, return False.
  • If no divisors are found, return True.
  • If not prime, increment num and repeat the check.
  • Once a prime is found, return that prime number.

Store the result in next_prime_greater.

Call previous_prime(given_value)

Decrement num by 1.

Check if num is Prime:

Start loop: Check divisibility from 2 to num - 1.

  • If num is divisible by any i, return False.
  • If no divisors are found, return True.
  • If not prime, decrement num and repeat the check.
  • Once a prime is found, return that prime number.

Store the result in previous_prime_lesser.

Program 2

Finding Prime Number Greater or Lesser Than a Given Value

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.
Theoretical Principles & Computational Physics Guide

Prime Search Near a Threshold: Next & Previous Prime Algorithms

Dr. Alorika Chatterjee & Dr. Anirban Shaw Science & Physics Learners Python 3 / NumPy / SciPy

1. Core Principles & Theoretical Framework

Threshold Seeking: Finds the immediate next prime $p > N$ or greatest prime $p < N$ relative to an arbitrary scientific threshold.
Prime Gap Bounds: Bertrand's postulate guarantees at least one prime exists between $N$ and $2N - 2$.
Cryptographic & Hashing Roles: Used in physics simulations for pseudo-random number generator modulus selection.

2. Mathematical Formulation & Algorithmic Pipeline

Prime gap $\Delta_p$ and Bertrand's Postulate guarantee:

$$ \forall N > 1, \quad \exists p \in \text{Primes} \quad \text{such that} \quad N < p < 2N - 2 $$

3. Numerical Mechanics & Implementation Logic

  • Search Direction: To find next prime, set candidate $c = N + 1$ (or $N + 2$ if $N$ is odd); increment by 2.
  • Primality Sub-Check: Apply the $\mathcal{O}(\sqrt{c})$ primality test to each candidate.
  • Termination: Break and return the first candidate satisfying primality criteria.

4. Relevant Computational Practice Exercises

Exercise 1
Find the nearest prime both above and below Avogadro's truncated integer representation $602214$.
Exercise 2
Compute and plot prime gaps $\Delta_n = p_{n+1} - p_n$ for the first 1000 primes above $10^4$.
Exercise 3
Verify Bertrand's Postulate computationally for 50 arbitrary values of $N \in [10^2, 10^5]$.
Standard Literature & References:
  • G. H. Hardy and E. M. Wright, "An Introduction to the Theory of Numbers", Oxford University Press (2008).