Given a limit, print all prime numbers smaller than or equal to the given limit.
Examples:
Input: limit = 10
Output: 2, 3, 5, 7
Input: limit = 20
Output: 2, 3, 5, 7, 11, 13, 17, 19
Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as:
Sieve of Atkin Approach: The sieve of Atkin is a modern algorithm for finding all prime numbers up to a specified integer.
Sieve of Atkin vs Sieve of Eratosthenes:
Compared with the ancient Sieve of Eratosthenes, which marks off multiples of primes, it does some preliminary work and then marks off multiples of squares of primes, that’s why it has a better theoretical asymptotic complexity with Complexity of (N / (log (log N)))
How Sieve of Atkin algorithm works:
The Sieve of Atkin algorithm works similarly to Sieve of Eratosthenes to filter out the composite numbers from a list of numbers, but this algorithm works in terms of modulo-60 remainders.
So we first assume all the numbers within limit to be composite, and then apply filter or sieve on them. If while any filter, the number appears to be prime, we mark it as prime and move on to the next number.
The filter or sieve in this algorithms works mainly 4 cases or layers:
- Case 1: If limit is greater than 2 or 3:
- The algorithm treats 2, and 3 as special cases and just adds them to the set of primes to start with.
- Case 2: if 4x2+y2=n is odd and modulo-12 remainder is 1 or 5
- Since all numbers with modulo-60 remainders 1, 13, 17, 29, 37, 41, 49, or 53 have a modulo-12 remainder of 1 or 5. Therefore, for this filter as well, we have to check if the number is 1 or 5 when taken modulo with 12.
- Also, These numbers are prime if and only if the number of solutions to 4x2+y2=n is odd and the number is square-free.
- A square-free integer is one that is not divisible by any perfect square other than 1.
- Case 3: if 3x2+y2=n is odd and modulo-6 remainder is 1
- All numbers with modulo-60 remainder 7, 19, 31, or 43 have a modulo-6 remainder of 1.
- These numbers are prime if and only if the number of solutions to 3x2 + y2 = n is odd and the number is square-free.
- Case 4: if 3x2-y2=n is odd and modulo-12 remainder is 11
- All numbers with modulo-60 remainder 11, 23, 47, or 59 have a modulo-12 remainder of 11.
- These numbers are prime if and only if the number of solutions to 3x2 – y2 = n is odd and the number is square-free.
- Case 5: Filtering out all the residual primes which have not yet been found
- Due to the filtering of the Sieve of Atkin algorithm, there might be some prime numbers who have been discarded or not found in the above cases.
- So to find out those, select all non-primes within limit, and mark all their squares as non-primes.
At the end of all of the filters above, the positions in the Sieve with a true value will be the list of primes within limit.
Illustration of Sieve of Atkin algorithm:
Consider limit as 20 and lets see how Sieve of Atkin algorithm generates primes up to 20:
Step 0: The status for all the numbers at the start is false. The special numbers are 2, 3, and 5, which are known to be prime.
Step 1: Generate values for the conditions.

Step 2: Flipping the status according to condition.
The above values of n in the table generated in the x, y loop will be tested for modulo conditions.
- Column 1: if (column1 value) % 12 == 1 or 5, then flip the sieve status for that number.
- Column 2: if (column2 value) % 12 == 7, then flip the sieve status for that number.
- Column 3: if (column3 value) % 12 == 11, then flip the sieve status for that number.
Note: Notice that we are taking mod with 12 in place of 60. This is because if we take mod 60 then we have to consider as many r as 1, 13, 17, 29, 37, 41, 49, or 53 and for all these r, mod 12 is 1 or 5. (done only to reduce the expression size)
Step 3: Checking for Square free Condition:
If any number in our list is the square of any number, then remove it.
Step 4: Creating an array of prime numbers for which status is true.
i.e. 2 3 5 7 11 13 17 19
Step 5: Print the output on the screen.
Sieve of Atkin algorithm step-by-step:
- Create a results list, filled with 2, 3, and 5.
- Create a sieve list with an entry for each positive integer; all entries in this list should initially be marked non-prime.
- For each entry number n in the sieve list, with modulo-sixty remainder r:
- If r is 1, 13, 17, 29, 37, 41, 49, or 53, flip the entry for each possible solution to 4x2 + y2 = n.
- If r is 7, 19, 31, or 43, flip the entry for each possible solution to 3x2 + y2 = n.
- If r is 11, 23, 47, or 59, flip the entry for each possible solution to 3x2 – y2 = n when x > y.
- If r is something else, ignore it completely…
- Start with the lowest number in the sieve list.
- Take the next number in the sieve list, still marked prime.
- Include the number in the results list.
- Square the number and mark all multiples of that square as non-prime. Note that the multiples that can be factored by 2, 3, or 5 need not be marked, as these will be ignored in the final enumeration of primes.
- Repeat steps four through seven.
Below is the implementation of the above algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
void SieveOfAtkin(int limit)
{
bool sieve[limit + 1];
for (int i = 0; i <= limit; i++)
sieve[i] = false;
if (limit > 2)
sieve[2] = true;
if (limit > 3)
sieve[3] = true;
for (int x = 1; x * x <= limit; x++) {
for (int y = 1; y * y <= limit; y++) {
int n = (4 * x * x) + (y * y);
if (n <= limit
&& (n % 12 == 1 || n % 12 == 5))
sieve[n] ^= true;
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve[n] ^= true;
n = (3 * x * x) - (y * y);
if (x > y && n <= limit
&& n % 12 == 11)
sieve[n] ^= true;
}
}
for (int r = 5; r * r <= limit; r++) {
if (sieve[r]) {
for (int i = r * r; i <= limit; i += r * r)
sieve[i] = false;
}
}
for (int a = 1; a <= limit; a++)
if (sieve[a])
cout << a << " ";
cout << "\n";
}
int main(void)
{
int limit = 19;
SieveOfAtkin(limit);
return 0;
}
|
Java
class GFG {
static void SieveOfAtkin(int limit)
{
if (limit > 2)
System.out.print(2 + " ");
if (limit > 3)
System.out.print(3 + " ");
boolean sieve[] = new boolean[limit+1];
for (int i = 0; i <= limit; i++)
sieve[i] = false;
for (int x = 1; x * x <= limit; x++) {
for (int y = 1; y * y <= limit; y++) {
int n = (4 * x * x) + (y * y);
if (n <= limit
&& (n % 12 == 1 || n % 12 == 5))
sieve[n] ^= true;
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve[n] ^= true;
n = (3 * x * x) - (y * y);
if (x > y && n <= limit
&& n % 12 == 11)
sieve[n] ^= true;
}
}
for (int r = 5; r * r <= limit; r++) {
if (sieve[r]) {
for (int i = r * r; i <= limit;
i += r * r)
sieve[i] = false;
}
}
for (int a = 5; a <= limit; a++)
if (sieve[a])
System.out.print(a + " ");
System.out.println();
}
public static void main(String[] args)
{
int limit = 20;
SieveOfAtkin(limit);
}
}
|
Python 3
def SieveOfAtkin(limit):
if limit > 2:
print(2, end=" ")
if limit > 3:
print(3, end=" ")
sieve = [False] * (limit + 1)
for i in range(0, limit + 1):
sieve[i] = False
x = 1
while x * x <= limit:
y = 1
while y * y <= limit:
n = (4 * x * x) + (y * y)
if (n <= limit and (n % 12 == 1 or
n % 12 == 5)):
sieve[n] ^= True
n = (3 * x * x) + (y * y)
if n <= limit and n % 12 == 7:
sieve[n] ^= True
n = (3 * x * x) - (y * y)
if (x > y and n <= limit and
n % 12 == 11):
sieve[n] ^= True
y += 1
x += 1
r = 5
while r * r <= limit:
if sieve[r]:
for i in range(r * r, limit+1, r * r):
sieve[i] = False
r += 1
for a in range(5, limit+1):
if sieve[a]:
print(a, end=" ")
limit = 20
SieveOfAtkin(limit)
|
C#
using System;
class GFG {
static void SieveOfAtkin(int limit)
{
if (limit > 2)
Console.Write(2 + " ");
if (limit > 3)
Console.Write(3 + " ");
bool[] sieve = new bool[limit + 1];
for (int i = 0; i <= limit; i++)
sieve[i] = false;
for (int x = 1; x * x <= limit; x++) {
for (int y = 1; y * y <= limit; y++) {
int n = (4 * x * x) + (y * y);
if (n <= limit
&& (n % 12 == 1 || n % 12 == 5))
sieve[n] ^= true;
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve[n] ^= true;
n = (3 * x * x) - (y * y);
if (x > y && n <= limit
&& n % 12 == 11)
sieve[n] ^= true;
}
}
for (int r = 5; r * r < limit; r++) {
if (sieve[r]) {
for (int i = r * r; i < limit;
i += r * r)
sieve[i] = false;
}
}
for (int a = 5; a <= limit; a++)
if (sieve[a])
Console.Write(a + " ");
Console.WriteLine();
}
public static void Main()
{
int limit = 20;
SieveOfAtkin(limit);
}
}
|
PHP
<?php
function SieveOfAtkin($limit)
{
if ($limit > 2)
echo 2 , " ";
if ($limit > 3)
echo 3 , " ";
$sieve[$limit+1] = 0;
for ($i = 0; $i <= $limit; $i++)
$sieve[$i] = false;
for ($x = 1; $x * $x <= $limit; $x++)
{
for ($y = 1; $y * $y <= $limit; $y++)
{
$n = (4 * $x * $x) + ($y * $y);
if ($n <= $limit
&& ($n % 12 == 1 || $n % 12 == 5))
$sieve[$n] ^= true;
$n = (3 * $x * $x) + ($y * $y);
if ($n <= $limit && $n % 12 == 7)
$sieve[$n] = true;
$n = (3 * $x * $x) - ($y * $y);
if ($x > $y && $n <= $limit
&& $n % 12 == 11)
$sieve[$n] ^= true;
}
}
for ($r = 5; $r * $r <= $limit; $r++) {
if ($sieve[$r]) {
for ($i = $r * $r; $i <= $limit;
$i += $r * $r)
$sieve[$i] = false;
}
}
for ($a = 5; $a <= $limit; $a++)
if ($sieve[$a])
echo $a , " ";
echo "\n";
}
$limit = 20;
SieveOfAtkin($limit);
?>
|
Javascript
<script>
function SieveOfAtkin(limit)
{
if (limit > 2)
document.write(2 + " ");
if (limit > 3)
document.write(3 + " ");
let sieve = new Array()
sieve[limit+1] = 0;
for (let i = 0; i <= limit; i++)
sieve[i] = false;
for (let x = 1; x * x <= limit; x++)
{
for (let y = 1; y * y <= limit; y++)
{
let n = (4 * x * x) + (y * y);
if (n <= limit && (n % 12 == 1 ||
n % 12 == 5))
sieve[n] ^= true;
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve[n] ^= true;
n = (3 * x * x) - (y * y);
if (x > y && n <= limit &&
n % 12 == 11)
sieve[n] ^= true;
}
}
for (let r = 5; r * r <= limit; r++) {
if (sieve[r]) {
for (i = r * r; i <= limit;
i += r * r)
sieve[i] = false;
}
}
for (let a = 5; a <= limit; a++)
if (sieve[a])
document.write(a , " ");
document.write("<br>");
}
let limit = 20;
SieveOfAtkin(limit);
</script>
|
Output
2 3 5 7 11 13 17 19
Time complexity: O(limit)
Auxiliary space: O(limit)
Similar Reads
Check for Prime Number
You are given a number n. Check whether it is a Prime number or not. Input: n = 10Output: falseExplanation: 10 is divisible by 2 and 5 Input: n = 11Output: trueExplanation: 11 is divisible by 1 and 11 only Input: n = 1Output: falseExplanation: 1 is neither composite nor prime Input: n = 0Output: fal
12 min read
Primality Test Algorithms
Introduction to Primality Test and School Method
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: true Input: n = 15Output: false Input: n = 1Outpu
11 min read
Fermat Method of Primality Test
Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Introduction to Primality Test and School MethodIn this post, Fermat's method is discussed. This method is a probabilistic method and is based on Fermat's Little Theorem.
10 min read
Primality Test | Set 3 (Miller–Rabin)
Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabili
15+ min read
Solovay-Strassen method of Primality Test
We have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (Miller–Rabin) The Solovay–Strassen primality test is a probabilistic test to determine if a number is c
15+ min read
Lucas Primality Test
A number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermat’s Little Theorem: If p is prime and
12 min read
Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. Example: Input : n =10Output : 2 3 5 7 Input : n = 20 Output: 2 3 5 7 11 13 17 19 The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller
9 min read
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime an
3 min read
Sieve of Eratosthenes in 0(n) time complexity
The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.Example : Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input :
12 min read
Programs and Problems based on Sieve of Eratosthenes
C++ Program for Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19". [GFGTABS] CPP // C++ program to print all primes smaller than or equal
2 min read
Java Program for Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19". Java Code // Java program to print all primes smaller than or equal to
2 min read
Scala | Sieve of Eratosthenes
Eratosthenes of Cyrene was a Greek mathematician, who discovered an amazing algorithm to find prime numbers. This article performs this algorithm in Scala. Step 1 : Creating an Int Stream def numberStream(n: Int): Stream[Int] = Stream.from(n) println(numberStream(10)) Output of above step is Stream(
4 min read
Check if a number is Primorial Prime or not
Given a positive number N, the task is to check if N is a primorial prime number or not. Print 'YES' if N is a primorial prime number otherwise print 'NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# - 1 , where pn# is the primorial of pn i.e the pro
10 min read
Sum of all Primes in a given range using Sieve of Eratosthenes
Given a range [L, R]. The task is to find the sum of all the prime numbers in the given range from L to R both inclusive. Examples: Input : L = 10, R = 20Output : Sum = 60Prime numbers between [10, 20] are:11, 13, 17, 19Therefore, sum = 11 + 13 + 17 + 19 = 60Input : L = 15, R = 25Output : Sum = 59Re
12 min read
Prime Factorization using Sieve O(log n) for multiple queries
We can calculate the prime factorization of a number "n" in O(sqrt(n)) as discussed here. But O(sqrt n) method times out when we need to answer multiple queries regarding prime factorization.In this article, we study an efficient method to calculate the prime factorization using O(n) space and O(log
11 min read
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
A number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so. Example: Input : from = 1, to = 20 Out
3 min read
Segmented Sieve
Given a number n, print all primes smaller than n. Input: N = 10Output: 2, 3, 5, 7Explanation : The output “2, 3, 5, 7” for input N = 10 represents the list of the prime numbers less than or equal to 10. Input: N = 5Output: 2, 3, 5 Explanation : The output “2, 3, 5” for input N = 5 represents the li
15+ min read
Segmented Sieve (Print Primes in a Range)
Given a range [low, high], print all primes in this range? For example, if the given range is [10, 20], then output is 11, 13, 17, 19. A Naive approach is to run a loop from low to high and check each number for primeness. A Better Approach is to precalculate primes up to the maximum limit using Sie
15 min read
Longest sub-array of Prime Numbers using Segmented Sieve
Given an array arr[] of N integers, the task is to find the longest subarray where all numbers in that subarray are prime. Examples: Input: arr[] = {3, 5, 2, 66, 7, 11, 8} Output: 3 Explanation: Maximum contiguous prime number sequence is {2, 3, 5} Input: arr[] = {1, 2, 11, 32, 8, 9} Output: 2 Expla
13 min read
Sieve of Sundaram to print all primes smaller than n
Given a number n, print all primes smaller than or equal to n. Examples: Input: n = 10Output: 2, 3, 5, 7Input: n = 20Output: 2, 3, 5, 7, 11, 13, 17, 19We have discussed Sieve of Eratosthenes algorithm for the above task. Below is Sieve of Sundaram algorithm. printPrimes(n)[Prints all prime numbers
10 min read
Bitwise Sieve
Given a number n, print all primes smaller than n.Examples : Input : 30 Output : 2 3 5 7 11 13 17 19 23 29 Input : n = 100 Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 We know how to calculate all primes less than n by the Sieve of Eratosthenes. Below is an impleme
15+ min read
Sieve of Atkin
Given a limit, print all prime numbers smaller than or equal to the given limit. Examples: Input: limit = 10Output: 2, 3, 5, 7 Input: limit = 20Output: 2, 3, 5, 7, 11, 13, 17, 19 Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as: Sieve of Eratosthenes:
15+ min read
Wheel Factorization Algorithm
Given a number N. The task is to check if the given number is Prime Number or not.Examples: Input: N = 987 Output: Not a Prime Number Explanation: As, 987 = 3*7*47. Therefore 987 is not a prime number.Input: N = 67 Output: Prime Number Wheel Factorization Method: Wheel Factorization is the improveme
9 min read
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
A prime number is a whole number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23. Given a range, L to R, the task is to generate all the prime numbers that exist in the Range. Examples Input: 1 10 Output 2 3 5 7 Input: 20 30 Output: 23
5 min read