Store and perform operations with huge numbers in iOS

Posted on

Store and perform operations with huge numbers in iOS

How could I handle operations with a number like:
48534588306961133067968196965257961415756656521818848750723547477673457670019632882524164647651492025728980571833579341743988603191694784406703

Nothing that I’ve tried worked so far… unsigned long, long long, etc…

Solution :

What you need is a library that provides support for operations on integers of arbitrary length. However, from what I’ve been able to find out, there are no such libraries written in Objective-C.

You are nevertheless in luck as Objective-C is a superset of C. That makes it possible for you to use C libraries such as those described in the answers to this somewhat dated SO question.

Also, since the Clang compiler supports C++ and combining Objective-C and C++ code, you can probably use something like big int.

Note that none of the built-in types is even close to being big enough to represent numbers with as many digits as your examples. The biggest available integer type is unsigned long long, if you don’t need negative numbers, and its size is 8 bytes/64 bits, which gives you a range of 0-18446744073709551615, or 20 digits max.

You could use JKBigInteger instead, it is a Objective-C wrapper around LibTomMath C library. And really easy to use and understand.

In your case:

JKBigInteger *int = [[JKBigInteger alloc] initWithString:@"48534588306961133067968196965257961415756656521818848750723547477673457670019632882524164647651492025728980571833579341743988603191694784406703"];

You can try here : http://gmplib.org/

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.

Leave a Reply

Your email address will not be published. Required fields are marked *