Interesting fact of the difference in time between this 2 methods... The second method just calculate only with needed numbers and dont iterate through a loop.
Example: 3 * (1+2+3+4...333) (Because 3 * 333 = 999 and 999 < 1000.
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
Calc calculator = new Calc();
long target = 999999999;
sw.Start();
Console.WriteLine("Result: " + (calculator.calcMultipleSumFast(3,target) + calculator.calcMultipleSumFast(5, target) - calculator.calcMultipleSumFast(15, target)));
sw.Stop();
Console.WriteLine("Runtime: " + sw.Elapsed);
Console.WriteLine();
sw.Start();
Console.WriteLine("Result: " + (calculator.calcMultiplesSum(3, 5,1000000000)));
sw.Stop();
Console.WriteLine("Runtime: " + sw.Elapsed);
Console.ReadKey();
}
public class Calc
{
public long calcMultiplesSum(long n1, long n2, long rangeMax)
{
long sum = 0;
for (long i = 0; i < rangeMax; i++)
{
if ((i % n1 == 0) || (i % n2 == 0))
{
sum = sum + i;
}
}
return sum;
}
public long calcMultipleSumFast(long n, long rangeMax)
{
long p = rangeMax / n;
return (n * (p * (p + 1))) / 2;
}
}
[![enter image description here][1]][1]
[1]: