Euler Project # 1

Can someone help me see the error in my logic.

Problem: Find sum of multiples of 3 and 5 less than 1000.


int sum = 0;
for(int i = 3; i < 1000; i++)
{
if( i % 3 == 0 || i % 5 == 0 )
sum += i;
} // answer is 233168, which is the correct one.

int sumOfDivisiblesByN(int number, int divisor)
{
int nthTerm = number - 1; // requirement of upper limit of sequence

return divisor * (nthTerm / divisor) * ((nthTerm / divisor) + 1) / 2;
// Sum of sequence S = {1,2,...n) = n(n+1)/2

}
int main()
{
cout << sumOfDivisiblesByN(1000,3) + SumOfDivisiblesByN(1000,5)
} // the answer here is 266333, which is wrong
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int sumOfDivisiblesByN( int number, int divisor )
{
    int nthTerm = number - 1; // requirement of upper limit of sequence

    return divisor * (nthTerm / divisor) * ((nthTerm / divisor) + 1) / 2;
    // Sum of sequence S = {1,2,...n) = n(n+1)/2
}

int main()
{
    const int UBOUND = 1000 ;

    std::cout << sumOfDivisiblesByN( UBOUND, 3 ) // sum of divisors by 3
                 + sumOfDivisiblesByN( UBOUND, 5 ) // plus sum of divisors by 5
                 - sumOfDivisiblesByN( UBOUND, 15 ) << '\n' ; // minus sum of divisors by 15
}
You sum some numbers twice. For example, the number 15 is divisble by 3 AND divisible by 5. You are summing it twice; once in sumOfDivisiblesByN(1000,3) and once in sumOfDivisiblesByN(1000,5)
Last edited on
Thanks JLBorges and Repeater!
Topic archived. No new replies allowed.