From 2fe4b589b14e2210ae13197a6d2671e8585ca96d Mon Sep 17 00:00:00 2001 From: Michael Ieraci <152013310+mieraci22@users.noreply.github.com> Date: Fri, 10 Jan 2025 10:53:40 -0500 Subject: [PATCH] Update primes.py updated isPrime func to use math instead of scipy --- primes.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/primes.py b/primes.py index 7b625e3..cc4482f 100644 --- a/primes.py +++ b/primes.py @@ -9,7 +9,7 @@ """ Import libraries. """ -import scipy, pylab +import scipy, pylab, math def isEven(n): """ @@ -22,24 +22,25 @@ def isEven(n): def isPrime(n): """ - Function which returns True if the integer n is prime. Tests integers - d from two up to Dmax = scipy.sqrt(n), stopping if any are divisors of n - (or, test if n is even and then test odd divisors). This is most naturally - done using the "while" command, - while n%d != 0 and d <= Dmax: - d+=1 [or 2] - What condition will d satisfy after the while loop if n is prime? + Function which returns True if the integer n is prime. + Tests integers d from 2 up to sqrt(n), stopping if any are divisors of n. + Uses an optimized approach by checking for even numbers first + and then testing odd divisors. """ - Dmax = scipy.sqrt(n) + if n < 2: + return False if n == 2: return True - if isEven(n): + if n % 2 == 0: return False + + Dmax = math.sqrt(n) d = 3 - while n%d != 0 and d <= Dmax: - d += 2 - return d > Dmax + while d <= Dmax and n % d != 0: + d += 2 # Only test odd numbers + return d > Dmax + def primeList(nMax): """ Returns a list of all prime numbers less than nMax.