Rather than using range/loop based solutions you may wish to leverage more math than brute force.
There is a simple way to get the sum of multiples of a number, less than a number.
For instance, the sum of multiples of 3 up to 1000 are: 3 + 6 + 9 + ... + 999
Which can be rewritten as: 3* ( 1 + 2 + 3 + ... + 333)
There is a simple way to sum up all numbers 1-N:
Sum(1,N) = N*(N+1)/2
So a sample function would be
unsigned int unitSum(unsigned int n)
{
return (n*(n+1))/2;
}
So now getting all multiples of 3 less than 1000 (aka up to and including 999) has been reduced to:
3*unitSum((int)(999/3))
You can do the same for multiples of 5:
5*unitSum((int)(999/5))
But there is a caveat! Both of these count multiples of both such as 15, 30, etc
It counts them twice, one for each. So in order to balance that out, you subtract once.
15*unitSum((int)(999/15))
So in total, the equation is:
sum = 3*unitSum((int)(999/3)) + 5*unitSum((int)(999/5)) - 15*unitSum((int)(999/15))
So now rather than looping over a large set of numbers, and doing comparisons, you are just doing some simple multiplication!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…