Use theThe Math, @Heslacher ...
... well ok, in the case of one or two arguments, there's a simple math solution. Instead of iterating over the numbers in the range and performing modulo,
you can you could:
The code becomesWith a helper function:
int sum =private 0;
foreachint SumOfMultiples(int multipletarget, inint multiplesmultiple) {
int count = (target - 1) / multiple;
sum +=return multiple * count * (count + 1) / 2;
}
return sum;
... unfortunately ...
As @BorisTheSpider pointed out in This gives a comment, andstraight \$O(1)\$ solution for one multiple.
@Edward demonstrated in his answerFor two multiples a and b,
this algorithm results in double-countingyou cannot simply sum them as that would include the common multiples.
So in case of 3 and 5their multiples twice. So after summing, you would have to subtractsubtract the multiples of 3 * 5a * b:
return SumOfMultiples(target, a)
+ SumOfMultiples(target, b)
- SumOfMultiples(target, a * b);
Thanks for @MartinR for the hint,
and @BorisTheSpider to point out the problem with my original answer that didn't subtract.