Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A value larger than ULong? Computing 100!

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?

like image 774
Chris Avatar asked Aug 12 '09 17:08

Chris


People also ask

How many digits in ulong?

MaxValue, ulong. This number is 20 digits long, which is adequate for many purposes even in the hard sciences. The ulong type uses all of its bits for storing a positive value. Minimum The minimum value of the ulong type is zero. This is because it has no sign bit, which is why it is called an unsigned value.

What is a ulong in c#?

ulong is a keyword that is used to declare a variable which can store an unsigned integer value from the range 0 to 18,446,744,073,709,551,615. It is an alias of System. UInt64. ulong keyword occupies 8 bytes (64 bits) space in the memory.

Can Double hold long?

In an article on MSDN, it states that the double data type has a range of "-1.79769313486232e308 .. 1.79769313486232e308". Whereas the long data type only has a range of "-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807".


3 Answers

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.

like image 86
Sam Harwell Avatar answered Sep 19 '22 00:09

Sam Harwell


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

like image 35
Andrew Hare Avatar answered Sep 20 '22 00:09

Andrew Hare


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.

like image 32
Robert L Avatar answered Sep 21 '22 00:09

Robert L