c++ - Project Euler #10 How to pre-calculate sum of primes? -
here question:
the sum of primes below 10 2+3+5+7=17.
find sum of primes not greater given n.
input format : first line contains integer t i.e. number of test cases. next t lines contains integer n.
output format : print value corresponding each test case in seperate line.
constraints : 1≤t≤104 1≤n≤106
https://www.hackerrank.com/contests/projecteuler/challenges/euler010 link question.
so, attempted solve question using sieve of eratosthenes. pre calculated primes below 10^6 given limit n.
6 out of 7 test cases accepted last test case give timeout(tle) .
i read discussion forum , there in order solve question need pre-calculate sums of primes also.
so, tried making array of long long ints , tried storing sums in it. giving me segmentation fault.
so, how supposed precalculate sums of primes?
here code:
#include "header.h" //max defined 1000000 bool sieve[max + 1]; // false = prime, true = composite int main(void){ //0 , 1 not primes sieve[0] = sieve[1] = true; //input limiting value int n = max; //cross out numbers for(int = 4; <= n; += 2){ sieve[i] = true; } //use sieve of eratosthenes for(int = 3; <= static_cast<int>(sqrt(n)); += 2){ if(sieve[i] == false){ for(int j = * i; j <= n; j += i) sieve[j] = true; } } long long p, ans = 0; int t; std::cin >> t; while(t--){ std::cin >> p; for(int = 0; <= p; ++i) if(sieve[i] == false) ans += i; std::cout << ans << std::endl; ans = 0; } return 0; }
given array of primes prime[n]
, precomputing sums of primes can done in single for
loop this:
int sum[n]; sum[0] = primes[0]; (int = 1 ; < n ; i++) { sum[i] = prime[i]+sum[i-1]; }
you can use array primes[]
running binary search on primes
, , picking sum
@ same position if number being searched prime, or @ prior position if number not prime.
Comments
Post a Comment