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

กรกฎาคม 30th, 2009 Kowit Leave a comment Go to comments

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

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
Categories: Programming, Python Tags:
  1. No comments yet.
  1. No trackbacks yet.