Really Large Numbers
I'm writing an iPhone application. Say I have a whole number of LENGTH 256, i.e. 94736 has length 5, 3745, has length 4, etc. What kind of data type can开发者_Go百科 fit a number of length 256?
Does it have to be a number? Will you be doing math operations with it? If not, you should just use NSString.
The maximum value for an NSInteger is NSIntegerMax
, which in the iphone is 32 bit.
(2.147.483.647)
But you should treat a number on 256 ciphers as a NSString.
(from Foundation Constants Reference)
I think you can use double, but being limited to available precision. Or maybe you can store it as string and write your own functions to manipulate them, such as plus, minus. This could be hard.
You should look at NSDecimalNumber
its a wrapper an immutable wrapper for doing arithmetic on numbers on numbers expressed as *mantissa * 10^exponent*, where mantissa mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
It is not a fit if your requirement of a 256 digit mantissa is a hard requirement. It is a fit if you want to be able to work on numbers on that order.
If you really have need for numbers of that size with perfect precision then look into the GNU MP Bignum Library at http://gmplib.org/. The limit for numbers that GNU MP can support is only limited by available RAM. It is written in C, so easily usable as-is for an iPhone application.
For a school project I worked with numbers of length 256 + . The way I got around it was to build a class to store the numbers as arrays.
For example I would store 345 as [3,4,5]. This way you are only limited to the amount of memory available.
I wrote methods for multiplication, addition and subtraction of positive numbers. Not too hard, and it works well.
I would suggest the same thing if you are looking at doing math with the numbers. Then just implement the functions you need.
This was done in c++ using xcode as compiler.
The maximum number is 10^256 - 1 (10 to the power of 256 minus 1)
精彩评论