Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //terina burr
- //section one
- //assignment three
- //due 9/21/15
- #include <iostream>
- #include <set>
- #include <cstdlib>
- #include <iomanip>
- using namespace std;
- int ITEM_W = 5;
- int NO_ITEMS =10;
- void sieve( set<int>& s, int n) ;
- void print_primes( const set<int>& s) ;
- int main() {
- set<int> s;
- sieve(s, 1000);
- print_primes(s);
- return 0;
- }
- /***************************************************************
- Function: sieve
- Use: it applies the sieve of eratosthesis algorithm to take out all the numbers that are not prime
- Arguments: 1. s: the set that you are going to go through
- 2. n: the last number in the set
- Returns: nothing
- ***************************************************************/
- void sieve(set <int> &s, int n)
- {
- int m, i;
- s.erase(s.begin(), s.end());
- //erases everything that is in the set
- for(m =2; m<n; m++)
- s.insert(m);
- //inserts m if it is less than the limit
- for(m=2; m*m<=n; m++)
- //finds all number using the sieve of erat
- //it looks at the numbers from 2 to m*m<=2
- if(s.find(m) !=s.end())
- {
- //checks to see if m is in the set
- i=2*m;
- //if not then it removes multiples of m starting with 2*m
- while (i<=n)
- {
- s.erase(i);
- i+=m;
- //i is multiples of m
- }
- }
- }
- /***************************************************************
- Function: print_primes
- Use: prints all items in the set with NO_ITEMS per line and ITEM_W on how far apart they are
- Arguments: 1. s: the set that you are going to go through
- Returns: nothing
- ***************************************************************/
- void print_primes(const set<int> &s)
- {
- set<int>::iterator iter;
- int count =0;
- iter = s.begin();
- cout << "There are " << s.size() << " prime numbers: " <<endl;
- while(iter !=s.end())
- {
- count++;
- cout << setw(ITEM_W) << *iter;
- //prints the numbers at a width that is four spaces apart
- if(count % NO_ITEMS == 0)
- {
- cout <<endl;
- }
- //if there is more than 16 numbers on a line then they start a new line
- iter++;
- }
- cout<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement