Making Sieve of Eratosthenes more memory efficient in python?

前端 未结 5 875
心在旅途
心在旅途 2021-01-20 00:41

Sieve of Eratosthenes memory constraint issue

Im currently trying to implement a version of the sieve of eratosthenes for a Kattis problem, however, I am running in

5条回答
  •  误落风尘
    2021-01-20 01:22

    I think you can try by using a list of booleans to mark whether its index is prime or not:

    def sieve_of_erato(range_max):
        primes_count = range_max
        is_prime = [True for i in range(range_max + 1)]
        # Cross out all even numbers first.
        for i in range(4, range_max, 2):
            is_prime[i] = False
            primes_count -=1
        i = 3
        while i * i <= range_max:
            if is_prime[i]:
                # Update all multiples of this prime number
                # CAREFUL: Take note of the range args.
                # Reason for i += 2*i instead of i += i:
                # Since p and p*p, both are odd, (p*p + p) will be even,
                # which means that it would have already been marked before
                for multiple in range(i * i, range_max + 1, i * 2):
                    is_prime[multiple] = False
                    primes_count -= 1
            i += 1
    
        return primes_count
    
    
    def main():
        num_primes = sieve_of_erato(100)
        print(num_primes)
    
    
    if __name__ == "__main__":
        main()
    

    You can use the is_prime array to check whether a number is prime or not later on by simply checking is_prime[number] == True.

    If this doesn't work, then try segmented sieve.

    As a bonus, you might be surprised to know that there is a way to generate the sieve in O(n) rather than O(nloglogn). Check the code here.

提交回复
热议问题