Now I am doing Project Euler number 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
This is my code, which runs in 0 milliseconds:
static void Main(string[] args)
{
Stopwatch s = new Stopwatch();
s.Start();
int sumNums = 0;
for(int i = 0; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0) { sumNums += i; }
}
s.Stop();
Console.WriteLine(sumNums);
Console.WriteLine(s.ElapsedMilliseconds);
}
I also have this version, which also runs in 0 milliseconds. In fact, running both methods in the same timer together results in 0 milliseconds:
static void Main(string[] args)
{
Stopwatch s = new Stopwatch();
s.Start();
int sumNums = 0;
for (int i = 0; i < 1000; i += 3)
{
sumNums += i;
}
for (int i = 0; i < 1000; i += 5)
{
sumNums += i % 3 == 0 ? 0 : i;
}
s.Stop();
Console.WriteLine(sumNums);
Console.WriteLine(s.ElapsedMilliseconds);
}
What could be improved, and which version is better?
3 + 6 + 9 + .... 999 = 3 * (1 + 2 + 3 + .... 333)
and similarly, answer to your problem is3 * Math.Floor(n / 3) * (Math.Floor(n / 3) + 1) / 2 + 5 * Math.Floor(n / 5) * (Math.Floor(n / 5) + 1) / 2 - 15 * Math.Floor(n / 15) * (Math.Floor(n / 15) + 1) / 2
Note - This assumes that if you want sum below 1000, then you use 999 as n above \$\endgroup\$F(a, n) = a * Math.Floor(n / a) * (Math.Floor(n / a) + 1) / 2
, then the answer isF(3, 999) + F(5, 999) - F(15, 999)
\$\endgroup\$