patterncsharpMinor
Factorial/permutations/combinations program
Viewed 0 times
factorialprogramcombinationspermutations
Problem
I wrote a factorial/permutations/combinations program in Java, and I want to do the same in C#. I noticed (from various research) that when you use the
ulong variable type, the max value is higher than Java's long. My limitation in the Java version was that the long type was too small to do numbers like 30, or 100. I wrote a little thing that would test if my hypothesis that C# could stretch the range of my program, but I was proven wrong. My Java version can reach approximately 24, but the C# goes to roughly 20. Is there anything I can do to reach my goal?using System;
namespace codeAdmiral{
public class Factorial{
public static void Main(){
ulong num;
Console.WriteLine("Enter value");
num = ulong.Parse(Console.ReadLine());
ulong factorial = 1;
for (ulong forBlockvar = num; forBlockvar > 1; forBlockvar--){
factorial *= forBlockvar;
}
Console.WriteLine("The Factorial for the Given input is:");
Console.WriteLine(factorial);
}
}
}Solution
Signed 64-bit integer (
Because of this, 20! should be computed correctly both in Java and c#, but 21! should be incorrect in both, no matter whether you use
If you want to make sure you are getting correct results in C#, you can use
What should you do if you want to compute larger values than 20!? The best option would be if there was some type that could represent arbitrarily large integers. Fortunately, both languages have them, there is
long in both Java and C#) can have values between approximately -9 · 1018 and 9 · 1018. Unsigned 64-bit integer (ulong in C#) can have values between 0 and approximately 1.8 · 1019. The value of 20! is approximately 2 · 1018, so it fits comfortably both to long and ulong. The value of 21! is approximately 5 · 1019, so it doesn't fit even into ulong.Because of this, 20! should be computed correctly both in Java and c#, but 21! should be incorrect in both, no matter whether you use
long or ulong.If you want to make sure you are getting correct results in C#, you can use
unchecked. If you do that and the computation overflows, you will get an exception.What should you do if you want to compute larger values than 20!? The best option would be if there was some type that could represent arbitrarily large integers. Fortunately, both languages have them, there is
BigInteger in C# and BigInteger in Java.Context
StackExchange Code Review Q#12165, answer score: 8
Revisions (0)
No revisions yet.