Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2503
旧巷少年郎
旧巷少年郎 2020-11-22 04:40

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

17条回答
  •  自闭症患者
    2020-11-22 04:56

    I figured it must be possible to simply use the empty list as the terminating condition for the loop and came up with this:

    limit = 100
    ints = list(range(2, limit))   # Will end up empty
    
    while len(ints) > 0:
        prime = ints[0]
        print prime
        ints.remove(prime)
        i = 2
        multiple = prime * i
        while multiple <= limit:
            if multiple in ints:
                ints.remove(multiple)
            i += 1
            multiple = prime * i
    

提交回复
热议问题