Programming,  Python

จำนวนเฉพาะกับตะแกรงเอราทอสเทนีส

ไปอ่านเจอมา เขียนไว้กันลืม

def primes(n):
"""
primes(n) --> primes
Return list of primes from 2 up to but not including n.
Uses Sieve of Erasth.
"""
    if n < 2:
        return []
    nums = range(2,int(n))
    p = []
    while nums:
        new_prime = nums[0]
        p.append(new_prime)
        for i in nums[1:]:
            if i % new_prime == 0:
                nums.remove(i)
        nums.remove(nums[0])
    return p

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: