Calculating very large whole numbers
I am trying to compute 2^1000 (2 to the power of 1000) using c#. I need the value to all places. I've been scratching my head for a while now because I can't seem to figure out a way to achieve this in c#.
Is there some kind of type that will store a number 300+ digits long, that I开发者_JAVA技巧'm missing? :)
Thanks
Yes, but only in .NET 4.0 - System.Numerics.BigInteger
.
If you can use .NET 4.0, I'd go for that. Otherwise, I'm sure there are third party libraries around. Let me know if you want me to try to find some.
If your goal is to exercise your C# skills on Euler problems, then using a BigInt library seems pointless. If you just need the value of 2^1000 as a step to solving another problem, well, here it is.
10715086071862673209484250490600018105614048117055
33607443750388370351051124936122493198378815695858
12759467291755314682518714528569231404359845775746
98574803934567774824230985421074605062371141877954
18215304647498358194126739876755916554394607706291
4571196477686542167660429831652624386837205668069376
System.Numerics.BigInteger if you're in .net 4.0 (VS 2010)
Or, look for a good bigint implementation on the web - there are many to choose from.
See also this StackOverflow question.
You could use an array to store your digits. It's messy I know, but essentially you will have to program multiplication as you would do it by hand, except in your code.
You could just use F# to test do it, as that will work in VS2008, but for a production application it would be a problem.
Look at Problem #25, http://blogs.msdn.com/mpeck/archive/2009/04/01/solving-problems-in-c-and-f-part-2.aspx, as it will show an approach that you may be able to use.
Your C# application can call an F# class, they work together.
If you can use IronRuby (not sure how usable that is at the moment), it has implicit conversion to Bignum. Example:
2 ** 1000
gives:
107150860718626732094842504906000181056140...
I know this question is pretty old but it's still found by google. I had the same problem, I was looking for a library to calculate with huge (or small) numbers which cannot be represented by standard data types.
So I created a new data type called EDecimal
. With this data type you can calculate with numbers of arbitrary size and precision. It does not matter if the number has 10 digits or 1000000.
Just have a look at it at https://github.com/anakonda3000/HyperMath/
There is a class here called BigInt
Very useful for that type of problem without .Net 4.0
eh ... , 2^0 is 1st bit, 2^1 is 2nd bit , ... , 2^4 is 5th bit .... you need a 1000 bits for this . I do not know anything about c#, however, how about just remembering that the bitwise notation is a 999 0's with one 1 ? And use it accordingly.
What are you planning to use that number for?
You can add a reference to the Java runtime (C:\Windows\Microsoft.NET\Framework\v2.0.50727\vjslib.dll is what I've got) and using java.math
, you get a BigInteger
精彩评论