Define a function primesFrom: int -> int list that takes a positive number and r
ID: 650844 • Letter: D
Question
Define a function primesFrom: int -> int list that takes a positive number and returns the list of all prime numbers less than or equal to that number. While such a function can be constructed many ways, you must use the following approach: a number k should be added to the list if and only if it is not divisible by any prime number less than it. (I.e., take advantage of the fact that you may already have computed some prime numbers.) Your function should be reasonably efficient and avoid any unnecessary duplication of effort. You may assume that your function will be called with a positive numbe
Explanation / Answer
def primesFrom(n):
if (n == 1):
return []
l = [2]
for i in range(3,n+1):
t = True
for num in l:
if (i % num == 0):
t = False;
if (t == True):
l.append(i)
return l
print primesFrom(100)
# Idea : any composite number let say it x then x is always divided by atleast one of the prime number less than x.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.