C
C#3mo ago
2spooky2play

✅ Strange output of my code

var query = Enumerable.Range(1, 1000)
.Where(x => x % 2 == 0)
.Aggregate((x, y) => x * y);

Console.WriteLine(query);
var query = Enumerable.Range(1, 1000)
.Where(x => x % 2 == 0)
.Aggregate((x, y) => x * y);

Console.WriteLine(query);
why does this output 0? is it due to overflow, and if it is, why is an exception not thrown?
3 Replies
PixxelKick
PixxelKick3mo ago
By default overflow/underflow doesn't throw but you can enable it via a setting in your csproj: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/language#checkforoverflowunderflow Or by wrapping it in checked(...) IE in your case: .Aggregate((x, y) => checked(x * y))
C# Compiler Options - language feature rules - C#
C# Compiler Options for language feature rules. These options control how the compiler interprets certain language constructs.
PixxelKick
PixxelKick3mo ago
Since your math there is effectively doing 2^125250 I think, if I did the math right. 2x4x6x8x10....1000 Is the same as 2^(1+2+3+4+5...500) Which can then just be 2^(1+500+2+499+3+498...) Which becomes 2^(501+501+501...) = 2^(501*250) = 2^125250 = 37,704 digits long numbah
2spooky2play
2spooky2play3mo ago
cool, thank you!
Want results from more Discord servers?
Add your server
More Posts