Next Prime Number in Python

Question:

I’m a beginner in Python and I’m practicing to code this problem I saw. Next prime is needed, but there are limitations on the input. I have searched for similar questions, but my code is still not working. Hope you can help. Thank you!

The problem I get is when I enter 32, the results show 33 when the next prime is 37…

Here’s my code so far.

num = int(input("Enter a positive number:"))   

import math

def nextprime(n):
    if n < 0:
      raise ValueError
  
    for next in range(n + 1, n +200):
        if next > 1:
            for i in range(2, next):
                if (next % i) == 0:
                    break
                else:
                    return next
   
Asked By: PoohSan

||

Answers:

In your code when you arrive to a number that reminder is not zero you return that number. You need a flag for every number this flag is True if can be divide flag convert to False for the first number that flag not convert to false return that number like below.

Don’t use next because this is a builtin function.

Try this: (I don’t improve your code)

def nextprime(n):
    if n < 0:
      raise ValueError
  
    for i in range(n + 1, n +200):
        if i > 1:
            pr = True
            for j in range(2, i):
                if (i % j) == 0:
                    pr = False
                    break
            if pr:
                return i
    return 'not found'

You can also try this code, write function to check that a number is prime or not like def is_prime then for number of larger that you input num find min number next. (this answer from this thread.)

def is_prime(x):
    return all(x % i for i in range(2, x))

def next_prime(x):
    return min([a for a in range(x+1, 2*x) if is_prime(a)])

print(next_prime(32))

You can also use sympy like below: (this answer from this thread.)

from sympy import *
nextprime(32) 
Answered By: I'mahdi
def next_prime(n):
    while True:
        n=n+1
        for i in range (2,int(n/2)):
            if n%i==0:
                break
        else:
            return n


print(next_prime(67)) 
Answered By: Rajendra Kumbar

Few off-topic tips:

  1. as user1740577 mentioned, don’t use next as a variable name
  2. refrain from using eval when possible, it’s okay here, but in real project this will lead to big no-no.
  3. Place imports at the very top of your script
  4. Consider using variable names i and j only for iterations.
  5. For duplicate except blocks use (Error, Error)

As for solution to your problem, with some adjustments, if you don’t mind

def next_prime(n: int) -> int:
    if n < 0:
        raise ValueError('Negative numbers can not be primes')
    # Base case
    if n <= 1:
        return 2
    
    # For i as every odd number between n + 1 and n + 200
    for i in range(n + 1 + (n % 2), n + 200, 2):
        # For every odd number from 3 to i (3 because we covered base case)
        for j in range(3, i, 2):
            # If remained is equals to 0
            if not i % j:
                # break current loop
                break
        # If loop j didn't break [nobreak: ]
        else:
            return i
    raise RuntimeError('Failed to compute next prime number :c')


def main():
    while True:
        try:
            num = int(input('Enter positive number: '))
            print(f'Next prime is: {next_prime(num)}')
            break
        except ValueError:
            print('Please enter a positive integer!')


if __name__ == '__main__':
    main()
Answered By: Adam Bright

Made some speed improvements to the code from @rajendra-kumbar:

#!/usr/bin/env python

import sys
import time
import math

def next_prime(number):
    if number < 0:
        raise ValueError('Negative numbers can not be primes')
    # Base case
    if number <= 1:
        return 2

    # if even go back 1
    if number % 2 == 0:
        number -= 1
    while True:
        # only odds
        number += 2
        #only need to check up to and including the sqrt
        max_check = int(math.sqrt(number))+2
        # don't need to check even numbers
        for divider in range(3, max_check, 2):
            # if 'divider' divides 'number', then 'number' is not prime
            if number % divider == 0:
                break
        # if the for loop didn't break, then 'number' is prime
        else:
            return number

if __name__ == '__main__':
    number = int(sys.argv[1].strip())
    t0 = time.time()
    print('{0:d} is the next prime from {1:d}'.format(next_prime(number), number))
    run_time = time.time() - t0
    print('run_time = {0:.8f}'.format(run_time))

it is about twice as fast

Answered By: vossman77

You can try something like simple:

def is_prime(number:int):
 check = 0
 for i in range(2,number):
    if number % i == 0:
        check += 1
 if check == 0:
    return True
 else:
    return False

def next_prime(value):
 check = value + 1
 while is_prime(check) is False:
    check += 1
 return check

value = int(input("Insert the number: "))
print(next_prime(value))
Answered By: Stefan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.