#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()
{
constint 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)