Sieve of Eratosthnes in C++28 Aug 2024 | 9 min read designed to identify all prime numbers within a defined range or up to a specified limit 'n'. It is named after the ancient Greek mathematician Eratosthenes. This algorithm offers a systematic approach to sieving out non-prime numbers, making it an invaluable tool in number theory and various computational applications. The algorithm begins by creating a list of numbers from 2 to 'n' and initially assuming that all of them are prime. After that, it systematically marks the multiples of each prime number, starting with 2, which is the smallest prime. As it progresses, the algorithm incrementally uncovers the prime numbers within the given range. The key insight driving the Sieve of Eratosthenes is that any multiple of a prime number is itself composite (non-prime). Therefore, the algorithm efficiently filters out non-prime candidates by successively marking these multiples. The process continues until the square root of 'n' is reached, after which the remaining unmarked numbers are confirmed as prime. Initialization: Create a boolean array or vector of size 'n+1', where each element represents a number from 0 to 'n'. Initially, all elements are set to "true" to assume that all numbers are prime. Marking Non-Primes: Start with the first prime number, which is 2. Mark all multiples of 2 as non-prime by setting their corresponding array elements to "false". This step eliminates numbers like 4, 6, 8, 10, etc., from the list of potential prime numbers. Find the Next Unmarked Number: After marking multiples of 2, find the next unmarked number greater than 2. This number will be the next prime number. it's 3 in the first iteration. Repeat the Process: Continue the process by marking all multiples of the next prime number (3 in this case) as non-prime. In the next iteration, find the next unmarked number, which will be the next prime number (in this case 5), and repeat the process. Continue this iteration until the square root of 'n' is reached. Result: Once the process is complete, all unmarked numbers in the array are prime numbers. The algorithm has sieved out the non-prime numbers, leaving behind only the primes. The Sieve of Eratosthenes is highly efficient for finding prime numbers, especially when dealing with large ranges of numbers because it avoids the need for expensive prime testing operations for each number individually. Instead, it systematically eliminates multiples of known primes to identify new primes. Program-1:It is C++ code implementation of the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit 'n'. This code uses the basic approach with a boolean vector to mark prime and non-prime numbers: Output Enter the limit (n): 20 Prime numbers up to 20 are: 2, 3, 5, 7, 11, 13, 17, 19 Explanation:
Inside the sieveOfEratosthenes function:
Inside the loop:
In the main function:
Complexity Analysis: Time Complexity: Outer Loop: The outer loop in the sieveOfEratosthenes function iterates from 2 to the square root of 'n'. In Big O notation, this part has a time complexity of O(sqrt(n)). It is because we only need to consider prime numbers up to the square root of 'n' to eliminate multiples. Inner Loop: Inside the outer loop, there's an inner loop that marks the multiples of the current prime number 'p' as non-prime. The inner loop runs approximately 'n/p' times for each prime 'p'. As we progress, 'p' becomes larger, and the number of multiples it marks decreases. So, the sum of the iterations for all primes is roughly: n/2 + n/3 + n/4 + ... + n/p This series converges to n * (1/2 + 1/3 + 1/4 + ... + 1/p), which is approximately n * log(log(n)) in the worst case. Total Time Complexity: Combining the time complexities of the outer and inner loops, the overall time complexity of the Sieve of Eratosthenes is approximately O(sqrt(n) * log(log(n))). Space Complexity: The space complexity of the Sieve of Eratosthenes is determined by the space required to store the boolean vector isPrime, which has 'n + 1' elements. Therefore, the space complexity of the algorithm is O(n). Program-2:Another approach to implementing the Sieve of Eratosthenes algorithm in C++ is to use a more memory-efficient version that requires less space. This method uses a bitset instead of a boolean vector to reduce memory usage. Here's a C++ implementation using this approach: Output Enter the limit (n): 50 Prime numbers up to 50 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 Explanation:
Inside the sieveOfEratosthenes function:
Inside the loop:
In the main function:
Complexity Analysis: Time Complexity: Initialization phase involves setting up a bitset of size 1000001, representing numbers from 0 to 'n'. This initialization step takes O(n) time but can be considered constant for practical purposes due to the fixed size bitset. The core of the algorithm is the outer loop, responsible for prime detection. It iterates approximately sqrt(n) times (O(sqrt(n))) to identify primes. It is because there's no need to consider numbers larger than the square root of 'n' when looking for primes. The inner loop marks multiples of prime numbers as non-prime, and it runs roughly n * log(log(n)) times in total. This complexity arises because the number of iterations decreases as prime numbers are discovered, converging to n * log(log(n)) in the worst case. The total time complexity can be expressed as O(n + sqrt(n) + n * log(log(n))), encompassing initialization, prime detection, and marking multiples. In practice, the inner loop's contribution, n * log(log(n)), dominates the complexity. This detailed breakdown clarifies how time is distributed across various algorithmic steps, facilitating a comprehensive understanding of its efficiency. Space Complexity: Bitset for Prime Marking:
Additional Space: There are some additional variables used in the code, such as integer variables (n, p, i, first, etc.), which occupy a constant amount of memory. So, the space complexity for these variables is O(1). Next TopicBanker's Algorithm in C++ |
In this article, we will discuss how to find the maximum product subarray in C++. Find the largest product of the subarray of positive and negative integers in the given array. O(n) is the predicted time complexity, and the only usable extra space is O(1). Examples: Input: arr[] =...
3 min read
The fegetexceptflag function is part of the C standard library, specified explicitly in the <fenv.h> header. It is used for working with floating point exceptions in C programs. Floating point exceptions occur when certain arithmetic operations, such as overflow or invalid operations, result in exceptional conditions. Syntax...
4 min read
In the realm of software design, particularly when dealing with the creation of related objects or components, design patterns serve as valuable tools for simplifying development and fostering code maintainability. One such design pattern is the Abstract Factory pattern, which enables the creation of entire families...
10 min read
In this article, we will discuss a C++ program to check if a matrix is orthogonal or Not with its output. But before going to the program, we must know about the orthogonal. The orthogonal matrix is one in which the transpose of the original matrix and...
4 min read
: Reinterpret_cast is a potent and problematic casting operator in C++ that is employed for type conversions. Even if they are unrelated or incompatible, it enables you to convert a pointer of one type to a pointer of a different type. Because it might result in...
6 min read
In this tutorial, we will study the KMP algorithm in C++ with code implementation. Other algorithms used for pattern matching include the Naive Algorithm and the Rabin Karp Algorithm. If we compare the algorithms, the Naive method and Rabin Karp have a time complexity of O((n-m)*m);...
9 min read
What is a linked list? A linked list is a linear data structure that consists of a sequence of nodes, where each node stores a piece of data and a reference (pointer) to the node in the List. Linked lists are useful for storing data collections...
6 min read
Introduction: The default method of interacting with strings in C++ is called std::string since it provides users with a wide range of useful functionalities. Among many other string operations, std::string offers string operations, including looking for substrings, comparing strings, concatenating strings, and slicing strings. But each time...
5 min read
A loop control statement used to end a loop in C++ is called a break. The loop iterations end as soon as the break statement is met from inside the loop, and control is instantly transferred from the loop to the first statement after the loop. break;...
7 min read
In C++, what is cstdlib? The C++ Standard Library header file () is the header that contains one of the language's most extensively used libraries. This header specifies a set of methods and macros to help teams and technologies write efficient, high-performing, standardised C++ code. C++ is a...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India