Question: In python Improve the prime number function. Use the following algorithm: a) To check if a number is prime, only check odd numbers. Any even
In python Improve the prime number function. Use the following algorithm:
a) To check if a number is prime, only check odd numbers. Any even number is automatically not prime. (Note: if you use this method you may not see much time difference because the time is influenced by other things your computer is doing, and the difference is not that big)
Use this test code
import time # **** this is the primes from in class ****
def isprime(x): iamprime = True for y in range(2,x): if x % y == 0: iamprime= False break return iamprime
def primelist(n): ''' find n primes param: n = number of primes to find ''' p=[] thenumber = 2 while len(p) < n: if isprime(thenumber): p.append(thenumber) thenumber = thenumber+ 1 return p
# **** your improved prime list generation code
def primelistfaster(n): your faster prime code goes here
# ----------- main --------
n= 2000 # or some other number
now = time.time() p = primelist(n) print("first method =", time.time()-now, " seconds")
now = time.time() p = primelistfaster(n) print("fast method =", time.time()-now, " seconds")
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
