Recently I was playing on CodingGame, normally I use "for" the challenges, but this time I've been using "Enumerable.Range" and something weird happened.
If N = 1001, the value of "result1" should be 250500, but the output was 251502, why?
But when N = 1000, the values of result1 and result2 are equals, why?
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
class Solution
{
static void Main(string[] args)
{
int N = int.Parse("1001");
var list = Enumerable.Range(2, N);
long result1 = list.Sum(item =>
{
return item % 2 == 0 ? item : 0;
});
long result2 = 0;
for (int i = 2; i <= N; i )
{
if (i % 2 == 0) result2 = i;
}
Console.WriteLine(result1);
Console.WriteLine(result2);
}
}
CodePudding user response:
Enumerable.Range
like this
Enumerable.Range(2, 1001)
Generates 1001 numbers starting with 2. The second argument is the count of numbers to generate, not the end value. https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range?view=net-6.0
CodePudding user response:
It's just because the second argument of the Enumerable.Range
method is the count of elements but not the upper bound. Therefore the returning sequence is 2 .. 1002
.