Enumerate All Primes to N
Problem Statement
Write a program that takes an integer argument and returns all primes between 1 and that integer.
Problem Solving
- There is not much of any solving here as I already know an ancient and well known algorithm for this. It's called the Sieve of Eratosthenes.
- The idea is to create a list of all numbers to n.
- Then iterate all number from two and at each number keep marking the multiples of those numbers as false or -1.
- The iterate to the next non -1 number and do the same.
- Find Code here.
Learning
- Must always check for bounds.
- The time complexity is n2 and space in O(n).
- There is a way to save some space as the even numbers can be removed.
- std::iota in the numeric header is a library function that can fill array with increasing numbers.
- There is also a Segmented Sieve which is used for large ranges and by segmenting them into smaller chunks
- Since I could not understand all aspect of optimizations to this problem I am currently leaving behind this problem and moving on to next one.
No comments:
Post a Comment