Python Forum
Trying to find the next prime number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to find the next prime number
#7
For fun I used ideas from the sympy prime code referenced by DeaD_EyE and re-ran some comparisons based on the algorithms in my previous post. This is my modified is_prime code that uses a small list of known primes (range 2 to 199).
def is_prime(x):
    global count
    if x in small_primes:
        return True
    nmax = int(x**0.5) + 1
    for n in small_primes:
        count += 1
        if n > nmax:
            return True
        if x % n == 0:
            return False
    for n in range(211, nmax, 2):
        count += 1
        if x % n == 0:
            return False
    return True
The next prime after 10067 is 10069. To calculate this the algorithm posted by FirstBornAlbatross performs 15,733,439 modulo divisions. The algorithm above performs 27.

The next prime after 100,000 is 100,003. Calculating all primes between 100,001 and 200,000 in a less than efficient manner performed 1,256,391,701 modulo divisions as opposed to 104 by the algorithm above. On my laptop the runtime was 150 seconds vs too small to measure.

And the inefficiency isn't all due to searching for all primes between x+1 and 2x. I ran a test to compute the next prime for every number in the range 100,001 and 200,000. Using the list of small primes to reduce how many factors are used to test for "primeness", my algorithm only hand to perform 18,000,463 modulo divisions. That looks like a lot, but 18 million is pretty small when compared to 1.25 billion.
Reply


Messages In This Thread
RE: Trying to find the next prime number - by deanhystad - Aug-11-2023, 09:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,525 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  calculate the 10001st prime number topologh 7 6,404 Oct-05-2020, 07:41 PM
Last Post: deanhystad
  Prime number code ryfoa6 3 2,975 Mar-21-2020, 12:23 AM
Last Post: ryfoa6
  Trouble interpreting prime number code ryfoa6 1 2,330 Mar-20-2020, 03:47 PM
Last Post: stullis
  Prime number Python homework mkrisz98 11 5,801 May-10-2019, 05:23 PM
Last Post: mkrisz98
  How to find the accuracy vs number of neighbours for KNN vokoyo 3 3,259 Apr-10-2019, 03:46 AM
Last Post: scidam
  python age calculator need to find the number of years before they turn 100 not using orangevalley 4 10,182 Mar-26-2018, 04:44 AM
Last Post: PyMan
  how to find a next prime number? iamyourfather 2 6,603 Oct-01-2017, 04:21 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020