views:

229

answers:

5

I'm trying to compute 100! and there doesn't seem to be a built-in factorial function. So, I've written:

Protected Sub ComputeFactorial(ByVal n As ULong)
        Dim factorial As ULong = 1
        Dim i As Integer
        For i = 1 To n
            factorial = factorial * i
        Next
        lblAnswer.Text = factorial
    End Sub

Unfortunately, running this with the value of 100 for n rseults in

Value was either too large or too small for a UInt64.

So, is there a larger data type for holding numbers? Am i mistaken in my methods? Am I helpless?

A: 

You need an implementation of "BigNums". These are integers that dynamically allocate memory so that they can hold their value.

A version was actually cut from the BCL.

The J# library has an implementation of java.math.BigInteger that you can use from any language.

Alternatively, if precision/accuracy are not a concern (you only care about order of magnitude), you can just use 64-bit floats.

Frank Krueger
+1  A: 

Until you can use System.Numerics.BigInteger you are going to be stuck using a non-Microsoft implementation like BigInteger on Code Project.

Andrew Hare
+5  A: 

Sounds like Project Euler.

.NET 4.0 has System.Numerics.BigInteger, or you can pick up a pretty sweet implementation here:
C# BigInteger Class

Edit: treed :(

I'll add - the version at CodeProject has additional features like integer square root, a primality test, Lucas sequence generation. Also, you don't have direct access to the buffer in the .NET implementation which was annoying for a couple things I was trying.

280Z28
Indeed, Project Euler! I suppose I'll have to go with one of these other classes. Quite unfortunate!
Chris
Don't be upset - I was using the one from CodeProject when I put down some 80 problems in 7 days. I stopped shortly after - stupid ADD. :o
280Z28
A: 

decimal will handle 0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point(scale of zero)

curtisk
Value was either too large or too small for a Decimal.
Chris
+1  A: 

Hint: use an array to store the digits of the number. You can tell by inspection that the result will not have more than 200 digits.

Robert L