C
C#2y ago
Cloudy

❔ Why does factorial stop working at 33?

public static void Main(string[] args)
{
Console.WriteLine(Factorial(33)); // 3400198294675128320
}

public static long Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
public static void Main(string[] args)
{
Console.WriteLine(Factorial(33)); // 3400198294675128320
}

public static long Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
The correct answer should be 8.6833x10^36
9 Replies
MODiX
MODiX2y ago
Thinker
REPL Result: Success
long.MaxValue
long.MaxValue
Result: long
9223372036854775807
9223372036854775807
Compile: 364.501ms | Execution: 51.173ms | React with ❌ to remove this embed.
Thinker
Thinker2y ago
Integers aren't infinitely big, at some point the number will overflow
ero
ero2y ago
try wrapping that whole method in a checked block
Thinker
Thinker2y ago
Or if you really want practically infinite range then you could use BigInteger instead of long.
Cloudy
CloudyOP2y ago
That's sufficiently big enough yeah? I'll try that thanks
Thinker
Thinker2y ago
BigInteger can for all intents and purposes represent all integers.
Cloudy
CloudyOP2y ago
So it actually has no limits? Does it grow in memory as it increases like a list or something? Seems to be a byte array, pretty cool
Thinker
Thinker2y ago
Yep, so the biggest value that a BigInteger can represent is the maximum length of an array times the size in bits of a uint, which is 2^8589934364 - 1.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server