Sieve of Eratosthenes algorithm

后端 未结 14 1181
一生所求
一生所求 2020-12-15 12:55

I am currently reading \"Programming: Principles and Practice Using C++\", in Chapter 4 there is an exercise in which:

I need to mak

相关标签:
14条回答
  • 2020-12-15 13:12

    I have no idea why you're not getting all the output, as it looks like you should get everything. What output are you missing?

    The sieve is implemented wrongly. Something like

    vector<int> sieve;
    vector<int> primes;
    
    for (int i = 1; i < max + 1; ++i)
       sieve.push_back(i);   // you'll learn more efficient ways to handle this later
    sieve[0]=0;
    for (int i = 2; i < max + 1; ++i) {   // there are lots of brace styles, this is mine
       if (sieve[i-1] != 0) {
          primes.push_back(sieve[i-1]);
          for (int j = 2 * sieve[i-1]; j < max + 1; j += sieve[i-1]) {
              sieve[j-1] = 0;
          }
       }
    }
    

    would implement the sieve. (Code above written off the top of my head; not guaranteed to work or even compile. I don't think it's got anything not covered by the end of chapter 4.)

    Return primes as usual, and print out the entire contents.

    0 讨论(0)
  • 2020-12-15 13:15

    below is my version which basically uses a bit vector of bool and then goes through the odd numbers and a fast add to find multiples to set to false. In the end a vector is constructed and returned to the client of the prime values.

    std::vector<int>  getSieveOfEratosthenes ( int max )
    {
      std::vector<bool> primes(max, true);
      int sz = primes.size();
    
      for ( int i = 3; i < sz ; i+=2 )
        if ( primes[i] ) 
          for ( int j = i * i; j < sz; j+=i)
            primes[j] = false;
    
      std::vector<int> ret;
      ret.reserve(primes.size());
      ret.push_back(2);
    
      for ( int i = 3; i < sz; i+=2 )
        if ( primes[i] )
          ret.push_back(i);
    
      return ret;
    }
    
    0 讨论(0)
  • 2020-12-15 13:15

    Try this code it will be useful to you by using java question bank

    import java.io.*;
    
    class Sieve
    
    {
    
        public static void main(String[] args) throws IOException
    
        {
    
            int n = 0, primeCounter = 0;
    
            double sqrt = 0;
    
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    
            System.out.println(“Enter the n value : ”);
    
            n = Integer.parseInt(br.readLine());
    
            sqrt = Math.sqrt(n);
    
            boolean[] prime = new boolean[n];
    
            System.out.println(“\n\nThe primes upto ” + n + ” are : ”);
    
            for (int i = 2; i<n; i++)
    
            {
    
                prime[i] = true;
    
            }
    
            for (int i = 2; i <= sqrt; i++)
    
            {
    
                for (int j = i * 2; j<n; j += i)
    
                {
    
                    prime[j] = false;
    
                }
    
            }
    
            for (int i = 0; i<prime.length; i++)
    
            {
    
                if (prime[i])
    
                {
    
                    primeCounter++;
    
                    System.out.print(i + ” “);
    
                }
    
            }
    
            prime = new boolean[0];
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-15 13:17

    In the code fragment below, the numbers are filtered before they are inserted into the vector. The divisors come from the vector.

    I'm also passing the vector by reference. This means that the huge vector won't be copied from the function to the caller. (Large chunks of memory take long times to copy)

    vector<unsigned int> primes;
    
    void calc_primes(vector<unsigned int>& primes, const unsigned int MAX)
    {
        // If MAX is less than 2, return an empty vector
        // because 2 is the first prime and can't be placed in the vector.
        if (MAX < 2)
        {
             return;
        }
    
        // 2 is the initial and unusual prime, so enter it without calculations.
        primes.push_back(2);
        for (unsigned int number = 3; number < MAX; number += 2)
        {
            bool is_prime = true;
            for (unsigned int index = 0; index < primes.size(); ++index)
            {
                if ((number % primes[k]) == 0)
                {
                    is_prime = false;
                    break;
                }
            }
    
            if (is_prime)
            {
                primes.push_back(number);
            }
        }    
    }
    

    This not the most efficient algorithm, but it follows the Sieve algorithm.

    0 讨论(0)
  • Here is my version:

    #include "std_lib_facilities.h"
    //helper function:check an int prime, x assumed positive.
    bool check_prime(int x) {
        bool check_result = true;
        for (int i = 2; i < x; ++i){
            if (x%i == 0){
                check_result = false;
                break;
            }
        }
        return check_result;
    }
    
    //helper function:return the largest prime smaller than n(>=2).
    int near_prime(int n) {
        for (int i = n; i > 0; --i) {
            if (check_prime(i)) { return i; break; }
        }
    }
    
    
    vector<int> sieve_primes(int max_limit) {
        vector<int> num;
        vector<int> primes;
        int stop = near_prime(max_limit);
        for (int i = 2; i < max_limit+1; ++i) { num.push_back(i); }
        int step = 2;
        primes.push_back(2);
        //stop when finding the last prime
        while (step!=stop){
            for (int i = step; i < max_limit+1; i+=step) {num[i-2] = 0; }
            //the multiples set to 0, the first none zero element is a prime also step
            for (int j = step; j < max_limit+1; ++j) {
                if (num[j-2] != 0) { step = num[j-2]; break; }
            }
            primes.push_back(step);
        }
        return primes;
    }
    
    int main() {
        int max_limit = 1000000;
        vector<int> primes = sieve_primes(max_limit);
        for (int i = 0; i < primes.size(); ++i) {
            cout << primes[i] << ',';
        }
    }
    
    0 讨论(0)
  • 2020-12-15 13:21

    Here's my implementation not sure if 100% correct though : http://pastebin.com/M2R2J72d

    #include<iostream>
    #include <stdlib.h> 
    
    using namespace std;
    void listPrimes(int x);
    
    int main() {
    
        listPrimes(5000);
    }
    
    void listPrimes(int x) {
        bool *not_prime = new bool[x];
        unsigned j = 0, i = 0;
    
        for (i = 0; i <= x; i++) {
            if (i < 2) {
                not_prime[i] = true;
            } else if (i % 2 == 0 && i != 2) {
                not_prime[i] = true;
            }
        }
    
        while (j <= x) {
            for (i = j; i <= x; i++) {
                if (!not_prime[i]) {
                    j = i;
                    break;
                }
            }
            for (i = (j * 2); i <= x; i += j) {
                not_prime[i] = true;
            }
            j++;
        }
    
        for ( i = 0; i <= x; i++) {
            if (!not_prime[i])
                cout << i << ' ';
        }
    
        return;
    }
    
    0 讨论(0)
提交回复
热议问题