![]() |
VOOZH | about |
Given two numbers m and n as interval range, the task is to find the prime numbers in between this interval.
Examples:
Input: m = 1, n = 10
Output: 2 3 5 7
Explanation : Primes in range from 1 to 10 are 2, 3, 5 and 7Input : m = 10, n = 20
Output : 11 13 17 19
Explanation : Primes in range from 10 to 20 are 11, 13, 17 and 19
The simplest method to check if a number i is prime by checking every number from 2 to i-1. If the number n is divisible by any of these, it's not prime. We check if a number if prime or not in sqrt(i) time because we just check for factors from number 2 to sqrt(i). For more details Please refer to Check for Prime Number.
m to n2 to √n2 3 5 7
The idea is to precompute all prime numbers up to
nusing the Sieve of Eratosthenes. Initially, all numbers are marked as prime, then multiples of each prime number are marked as non-prime. After preprocessing, all prime numbers in the required range[m, n]can be collected efficiently.
2, mark all multiples of each prime number as non-prime m to nExample for n = 10
Initially:
2 3 4 5 6 7 8 9 10 -> all marked primeStep 1: p = 2
Mark multiples of 2:
4 6 8 10 -> not prime
Remaining:
2 3 5 7 9Step 2: p = 3
Mark multiples of 3:
9 -> not primeFinal Prime Numbers:
2 3 5 7
2 3 5 7