I have written a solution to problem 23 of Project Euler, and after doing some testing and editing, I've managed to get the run time down from 1.7443 seconds to 1.56616 seconds. The problem is
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
What are some other ways that I could improve this program? I'm pasting it entirely, and it should be noted that I'm compiling with g++ -o3.
#include <chrono>
#include <cmath>
#include <iostream>
#include <ctime>
#include <ratio>
int main()
{
//Value given in the question
const int LIMIT = 28124;
//Used to measure the runtime
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
//Sieve of Erasthotenes to remove a significant number of iterations in the next step
int rootMax = (int)sqrt((double)LIMIT);
bool set[LIMIT+1] = {0};
for(int i = 2; i <= rootMax; ++i)
{
if(!set[i])
{
for(int j = (i*i); j <= LIMIT; j += i)
{
set[j] = true;
}
}
}
bool isSumOfAb[LIMIT] = {0};
int abundant[6965];
int count = 0;
for(int i = 12; i < LIMIT; ++i) //This can start at 12, as we know that 12 is the 1st abundant number
{
if(!set[i]) // Prime numbers won't be abundant, so next number
{
continue;
}
int sum = 0;
for(int j = 1; j < i; ++j)
{
if(i % j == 0)
{
sum += j;
}
}
if(sum > i)
{
abundant[count] = i;
++count;
}
}
//Lots of work to do here.
//Establish all of the sums and compare
int a, c;
for(int i = 0; i < 6965; ++i)
{
a = abundant[i];
for(int j = i; j < 6965; ++j)
{
c = a + abundant[j];
//Big speed increase when made like this as opposed to `if(c <= LIMIT) isSumOfAb[c] = true;`
if(c > LIMIT)
{
break;
}else
{
isSumOfAb[c] = true;
}
}
}
int sum = 0;
for(int i = 24; i < LIMIT; ++i) //can start at 24, as that is the 1st sum of 2 abundant numbers
{
if(!isSumOfAb[i])
{
sum += i;
}
}
std::cout << "Sum: " << sum;
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "\nIt took me " << time_span.count() << " seconds.";
}