Sieve of Eratosthenes - print all primes smaller than or equal to number n.
Sun Feb 06 2022 05:18:47 GMT+0000 (Coordinated Universal Time)
Given a number n, print all primes smaller than or equal to n. Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the Eratosthenes method: When the algorithm terminates, all the numbers in the list that are not marked are prime. Explanation with Example: Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50. We create a list of all numbers from 2 to 50. STEP-1: According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it. STEP-2: Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it. STEP-3: We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it. STEP-4: We continue this process and our final table will look like below: STEP-5: So, the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.