Write Python code for Sieve of Eratosthenes
- User
Write Python code for Sieve of Eratosthenes
- Assistant
Certainly! Here's Python code implementing the Sieve of Eratosthenes algorithm to find all prime numbers up to a given number
n:pythondef sieve_of_eratosthenes(n): """ Finds all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm. Parameters: n (int): The upper limit of the range to look for prime numbers (inclusive). Returns: list: A list of prime numbers less than or equal to n. """ if n < 2: return [] # There are no prime numbers less than 2 # Initialize a boolean array of True values. Index i represents the number i. is_prime = [True] * (n + 1) is_prime[0] = False # 0 is not a prime number is_prime[1] = False # 1 is not a prime number # Only need to check for factors up to the square root of n for i in range(2, int(n**0.5) + 1): if is_prime[i]: # If i is a prime number # Mark multiples of i as non-prime for multiple in range(i*i, n + 1, i): is_prime[multiple] = False # Collect all prime numbers primes = [i for i, prime in enumerate(is_prime) if prime] return primes # Example usage: n = 50 prime_numbers = sieve_of_eratosthenes(n) print(f"Prime numbers less than or equal to {n}:") print(prime_numbers)Explanation:
The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. It does so efficiently by iteratively marking the multiples of primes as composite (non-prime).
Algorithm Steps:
-
Initialization:
- Create a list
is_primeof boolean values, with indices from0to .
- Create a list
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.