Lecture 1.4 - Python Recap - II
Lecture 1.4 - Python Recap - II
Madhavan Mukund
https://www.cmi.ac.in/~madhavan
def prime(n):
return(factors(n) == [1,n])
def firstprimes(m):
(count,i,pl) = (0,1,[])
while (count < m):
if prime(i):
(count,pl) = (count+1,pl+[i])
i = i+1
return(pl)
def prime(n):
result = True
for i in range(2,n):
if (n%i) == 0:
result = False
break # Abort loop
return(result)
def prime(n):
(result,i) = (True,2)
while (result and (i < n)):
if (n%i) == 0:
result = False
i = i+1
return(result)
Madhavan Mukund Python Recap – II PDSA using Python Week 1 4/5
Computing primes
Directly check if n has a factor between import math
2 and n − 1 def prime(n):
(result,i) = (True,2)
Terminate check after we find first while (result and (i <= math.sqrt(n))
factor if (n%i) == 0:
Breaking out of a loop result = False
i = i+1
Alternatively, use while
return(result)
Speeding things up slightly
Factors occur in pairs
√
Sufficient to check factors upto n
√
If n is prime, scan 2, . . . , n instead
of 2, . . . , n − 1