![]() |
VOOZH | about |
The Task is to print all prime numbers in a given range by taking a starting and ending number as input. A prime number is a number greater than 1 that has no divisors other than 1 and itself.
For example, in the range [2, 7], prime numbers are 2, 3, 5 and 7. Let's look at different ways
Sieve of Eratosthenes algorithms finds all prime numbers in a given range, especially for large intervals. It works by creating a boolean array where each index represents a number and values marked as True for prime and False for non-prime.
[2, 3, 5, 7]
Explanation: It creates a boolean list assuming all numbers are prime. Starting from 2 to √y, it marks multiples of each prime as False i.e., non-prime. After this, indices marked as True represent prime numbers in the range.
Trial Division Method involves checking each number in the interval individually for primality. For each number, we test divisibility from 2 to √n. If a number is divisible by any value in this range, it is not prime.
[2, 3, 5, 7]
Explanation: For n in the range, it checks if n is greater than 1. It then assumes n is prime and checks divisibility from 2 to √n. If n is divisible by any number in this range, it is marked as non-prime. If no divisors are found, n is added to the result list.
SymPy Library provides a built-in function called primerange(x, y) to generate prime numbers in a given range efficiently. Internally, SymPy uses optimized algorithms, including the sieve method.
Note: SymPy is an external Python library, not part of the standard Python installation, therefore it must be install first using command - "pip install sympy"
Output
[2, 3, 5, 7]
Explanation: primerange(x, y + 1) returns an iterator of prime numbers from x to y. The result is converted into a list and stored in primes.
This method checks for primality by dividing each number from 2 to n//2. If any divisor is found, number is not prime. This method is the least efficient and suitable only for small intervals.
[2, 3, 5, 7]
Explanation: The code checks each number from x to y. Numbers ≤ 1 are skipped. For each number, it tests divisibility from 2 to i//2. If divisible, it’s not prime; otherwise, it’s added to the result list.