Store and perform operations with huge numbers in iOS

前端 未结 3 1713
情歌与酒
情歌与酒 2020-12-19 19:07

How could I handle operations with a number like: 485345883069611330679681969652579614157566565218188487507235474776734576700196328825241646476514920257289805718335793417439

相关标签:
3条回答
  • 2020-12-19 19:27

    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.

    0 讨论(0)
  • 2020-12-19 19:34

    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"];
    
    0 讨论(0)
  • 2020-12-19 19:36

    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.

    0 讨论(0)
提交回复
热议问题