10 Summation of Primes

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

#include <iostream>
#include <fstream>
#include <limits>
#include <vector>

using namespace std;

void pause() { cin.ignore(numeric_limits<streamsize>::max(), '\n'); }

// This function is incredibly slow 
bool checkIfPrime(int number)
{
    long int count = 2;
    for (int j = 2; j <= number - 1; j++)
    {
        // 2) Check if actually prime
        if (number % j == 0)
        {
            return false;
        }

        else if (count == number - 1)
        {
            return true;
        }
        count++;
    }
}

// Method 2: Reading from a list of prime numbers
vector<long long int> readFile()
{
    ifstream inFile;
    inFile.open("primes1.txt");

    if (inFile.fail())
    {
        cerr << "Error opening file";
        exit(1);
    }
    vector <long long int> primes;
    long long int prime;

    while (inFile >> prime)
    {
        primes.push_back(prime);
    }

    return primes;
}

int main()
{
    vector <long long int> thePrimes = readFile();

    int count = 0;
    long long int sum = 0;
    int number = 2000000;

    while (true)
    {
        if (thePrimes[count] <= number)
        {
            sum += thePrimes[count];
            count++;
        }

        else
            break;
    }

    cout << sum;
    pause();
}

My biggest setback here was learning how to read files with visual studio. After a while, I have realized that it was nessessary to place your specific file in the directory folder, as well as add it in the resource files of VS.

Solution: 142913828922

Last updated