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
#9
I added Pedroski55's heuristic to is_prime().
def is_prime(x):
    # Check if x in small primes or in range of small primes
    if x in small_primes:
        return True
    if x < small_primes[-1]:
        return False

    # Check if x ends in digit that is divisible by 2 or 5
    if x % 10 not in (1, 3, 7, 9):
        return False

    # All non-prime numbers have a prime factor.  Check if
    # any of the small primes are a factor of x.
    nmax = int(x**0.5) + 1
    for n in small_primes:
        if n > nmax:
            return True
        if x % n == 0:
            return False

    # Brute force it the rest of the way.
    for n in range(211, nmax, 2):
        if x % n == 0:
            return False
    return True
I was surprised to find that this actually increases the number of modulo divisions by 10% I had to run the tests several times using different approaches to convince myself that this was true. I suppose that there are so many numbers not divisible by 2 or 5 that testing these numbers twice is inefficient.

I removed 2 and 5 from the list of small primes to prevent them being tested twice and repeated my tests. Now Pedroski55's heuristic is a 5% improvement over using the complete set of small primes.
Reply


Messages In This Thread
RE: Trying to find the next prime number - by deanhystad - Aug-14-2023, 01:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,477 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  calculate the 10001st prime number topologh 7 6,321 Oct-05-2020, 07:41 PM
Last Post: deanhystad
  Prime number code ryfoa6 3 2,931 Mar-21-2020, 12:23 AM
Last Post: ryfoa6
  Trouble interpreting prime number code ryfoa6 1 2,287 Mar-20-2020, 03:47 PM
Last Post: stullis
  Prime number Python homework mkrisz98 11 5,682 May-10-2019, 05:23 PM
Last Post: mkrisz98
  How to find the accuracy vs number of neighbours for KNN vokoyo 3 3,208 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,069 Mar-26-2018, 04:44 AM
Last Post: PyMan
  how to find a next prime number? iamyourfather 2 6,561 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