This is the solution to this question https://practice.geeksforgeeks.org/problems/sum-of-all-prime-numbers-between-1-and-n/0
method :
- used sieve of eratosthenes to find all the numbers from 1 to N(input) .
- 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 ...
- 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.
- 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