0

This is the solution to this question https://practice.geeksforgeeks.org/problems/sum-of-all-prime-numbers-between-1-and-n/0

method :

  1. used sieve of eratosthenes to find all the numbers from 1 to N(input) .
  2. Created an array s that stores the sum of all prime numbers from 1 to i(index of array). after taking in input: test cases and the values stored in an array ...
  3. selects the max N out of all test cases..calls the sieve function that finds the sum of all prime no.s till max N.
  4. The input array is traversed and the corresponding sum outputs are displayed.

this works for small values of N but for larger inputs it gives a set fault !

#include <iostream>
using namespace std;


void sieve(int s[], int n)
{
    int *a = new int[n + 1];
    for(int i = 0; i < n + 1; ++i)
        a[i] = 1;

    for(int i = 2; i < n + 1; ++i)
    {
        if(a[i])
        {
            int x;
            for(int j = 0; x = i * (i + j), x < n + 1; ++j)
            {
                a[x] = 0;
            }
        }
    }
    int sum = 0;
    for(int i = 2; i < n + 1; ++i)
    {
        // cout << a[i] << " ";

        if(a[i])
            sum += i;
        s[i] = sum;
    }
    //cout << endl;
    s[0] = s[1] = 0;
    /*for(int i = 2; i < n + 1; ++i)
    {
        cout << s[i] << " ";
    }
    cout << endl;*/
}

int main() {
    //code

    int t;
    cin >> t;
    int a[t];
    for(int i = 0; i < t; ++i)
    {
        cin >> a[i];
    }

    int max = a[0];

    for(int i = 1; i < t; ++i)
    {
        if(a[i] > max)
        {
            max = a[i];
        }
    }

    int s[max+1];

    sieve(s, max);

    for(int i = 0; i < t; ++i)
    {
        cout << s[a[i]] << endl;
    }

    return 0;
}

PS. sorry for the lack of comments..was in a hurry :P

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
dagwood
  • 379
  • 1
  • 2
  • 13
  • 2
    Every good C++ book will explain the difference between declaring objects in automatic (function local) versus dynamic (allocated with `new`) scope. The C++ book will probably also explain that variable-length arrays are not standard C++ as well, but that's just a minor point. Without fully understanding the limitations and applications of each one, you have this situation where a large array result in a crash, for some mysterious reason. This is why wasting time on useless online quiz sites like that one, instead of a C++ book, serves very little towards actually learning C++. – Sam Varshavchik Jan 05 '20 at 16:34
  • @SamVarshavchik okay, I hear what you are trying to say. any good c++ book you recommend ? – dagwood Jan 05 '20 at 18:09
  • @dagwood [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242/995714) – phuclv Jan 06 '20 at 01:42

0 Answers0