Python Program to Find Next Prime Number
def next_prime(n): while True: n += 1; if is_prime(n): return n.Examples
How to Think About It
Algorithm
Code
def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def next_prime(n): candidate = n + 1 while True: if is_prime(candidate): return candidate candidate += 1 print(next_prime(3)) # Output: 5
Dry Run
Let's trace input 3 through the code to find the next prime number.
Start checking from 4
candidate = 4
Check if 4 is prime
4 % 2 == 0, so 4 is not prime
Move to next candidate 5
candidate = 5
Check if 5 is prime
5 is not divisible by 2, so 5 is prime
Return 5 as next prime
next_prime(3) returns 5
| Candidate | Is Prime? |
|---|---|
| 4 | No |
| 5 | Yes |
Why This Works
Step 1: Check divisibility to find primes
The code tests if a number is prime by checking if it has any divisor other than 1 and itself using num % i == 0.
Step 2: Start from next number
It begins checking from the number just after the input to find the next prime.
Step 3: Return first prime found
Once a prime number is found, the function returns it immediately as the next prime.
Alternative Approaches
def next_prime_sieve(n): limit = n * 2 # simple limit sieve = [True] * (limit + 1) sieve[0], sieve[1] = False, False for i in range(2, int(limit ** 0.5) + 1): if sieve[i]: for j in range(i*i, limit + 1, i): sieve[j] = False for candidate in range(n+1, limit + 1): if sieve[candidate]: return candidate print(next_prime_sieve(10)) # Output: 11
from sympy import nextprime print(nextprime(10)) # Output: 11
Complexity: O(k * sqrt(m)) time, O(1) space
Time Complexity
For each candidate number k after input n, the code checks divisibility up to sqrt(m), where m is the candidate. This leads to O(k * sqrt(m)) time.
Space Complexity
The code uses only a few variables and no extra data structures, so space is O(1).
Which Approach is Fastest?
The sieve method is faster for ranges but uses more memory. The direct check is simple and uses less memory. Using a library like sympy is fastest and easiest if available.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct divisibility check | O(k * sqrt(m)) | O(1) | Simple, small inputs |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Finding many primes in a range |
| sympy nextprime | Optimized C code | Depends on library | Quick, reliable with external library |