Search code examples
c++sum

sum of all the numbers below 1000 that are multiples of 3 or 5


Project Euler problem 1 is: Find the sum of all the multiples of 3 or 5 below 1000

Here is my program, using two simple functions to work out the sum of all the multiples of 3 and all the multiples of 5 and then add them up:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;


int threeSum( void );

int fiveSum( void );


int main( int argc, char** argv )
{
    cout << "\n The sum of all the natural numbers below 1000 that are multiples of 3 or 5 = \n" << endl;

    cout << threeSum() + fiveSum() << endl << endl;

    system( "PAUSE" );
}


int threeSum( void )
{
    int sumSoFar = 0;

    for ( int i = 1 ; i < 1000 ; i++ )
    {
        if ( i % 3 == 0 )
                            sumSoFar = sumSoFar + i;
    }

    return sumSoFar;
}


int fiveSum( void )
{
    int sumSoFar = 0;

    for ( int i = 1 ; i < 1000 ; i++ )
    {
        if ( i % 5 == 0 )
                            sumSoFar = sumSoFar + i;
    }

    return sumSoFar;
}

which produces 266333 as the answer. Is this correct, or am I doing something wrong, as the website checker says this is the wrong answer!


Solution

  • As most others pointed out, you're summing the multiples of 15 twice.

    Just a hint for another solution:

    The sum of multiples of 3 below 1000 is

    SUMBELOW(3,1000) = 3 + 6 + 9 + ... + 999 = 3*(1+2+3+...+333) = 3*333*(1+333)/2 = 3*((1000-1)/3)*(1+(1000-1)/3)/2
    

    (All divisions are integer divisions...)

    There are similar formulas for calculating the sums of multiples of 5 and 15. To get the overall result, you have to add the sums for 3 and 5 and subtract the sum for 15...