I am trying to test the performance of three solutions for the Problem 1 from projecteuler.net by passing an int.MaxValue
instead of 1000.
First solution:
long sum = SumDivisibleBy(3) + SumDivisibleBy(5) - SumDivisibleBy(15);
Console.WriteLine(sum);
Where SumDivisibleBy is:
public static long SumDivisibleBy(int k, int n = int.MaxValue)
{
long m = n / k;
return k * (m * (m + 1) / 2);
}
is faster (about 27 seconds) than
second solution:
long sum = 0;
for (int i = 0; i < int.MaxValue; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
sum += (long)i;
}
}
Console.WriteLine(sum);
The third solution (which is an elegant one in my opinion) is:
Console.WriteLine(Enumerable.Range(1, 999)
.Where(x => x % 3 == 0 || x % 5 == 0)
.Sum());
but I cannot achieve this (for testing performance purpose):
Console.WriteLine(Enumerable.Range(1, int.MaxValue)
.Where(x => x % 3 == 0 || x % 5 == 0)
.Sum());
because it gives me an OverflowException
which is natural because of the nature of int Sum(this IEnumerable<int> source)
.
My question is this:
How can I upcast the int Sum(this IEnumerable<int> source)
to the long Sum(this IEnumerable<long> source)
in the code below:
Console.WriteLine(Enumerable.Range(1, int.MaxValue)
.Where(x => x % 3 == 0 || x % 5 == 0)
.Sum());