Prompt: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
Code:
#include <iostream>
#include <list>
/**
* @brief Searches for numbers that in a that can be factored by b
*
* @param a list of numbers
* @param b factorable number
*/
void search(std::list<long long>& a, long long b, std::list<long long>::iterator c);
int main() {
std::list<long long> nums;
long long range = 0;
long long PrimesSum = 0;
std::cout << "Sum all the primes up to: ";
std::cin >> range;
for (int i = 2; i <= range; i++) {
nums.push_back(i);
}
for (std::list<long long>::iterator it = nums.begin(); it != nums.end(); it++) {
search(nums,*it,it);
}
for (std::list<long long>::iterator it = nums.begin(); it != nums.end(); it++) {
PrimesSum+=*it;
}
std::cout << "The sum of all primes below " << range << " is " << PrimesSum << ".\n";
}
void search(std::list<long long>& a, long long b, std::list<long long>::iterator c) {
std::list<long long>::iterator it = c;
while (it != a.end()) {
if (*it % b == 0 && *it != b) {
a.erase(it);
}
it++;
}
}
Problem: I am getting a segmentation fault for values above 46998. Anything equal to or less than 46998 will work as expected. Could I get some help as to what I'm doing wrong or what I can improve?