41

Is there an equivalent to Java's BigInteger class in Swift? I am tying to do large calculations in Swift with positive integers larger than UInt64 maximum valye.

What is the best way to handle these numbers in Swift?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
liam923
  • 991
  • 1
  • 10
  • 19
  • 1
    Decimal types are generally for financial calculation, not just arbitrary precision. In Java you want BigInteger, as your title indicates, not BigDecimal as your question body indicates. Cocoa does not include any BigInteger type. – bames53 Aug 27 '14 at 19:26

6 Answers6

13

You can use the NSDecimalNumber class from Cocoa. It is not infinite precision, but it can represent 38 decimal digits of precision, which may be enough for what you need.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
newacct
  • 119,665
  • 29
  • 163
  • 224
10

I found a prototype of BigInt in the official Swift repository: https://github.com/apple/swift/blob/master/test/Prototypes/BigInt.swift

You can probably just copy it into your project and use it. Maybe some day it will be added to the standard library.

Richard Venable
  • 8,310
  • 3
  • 49
  • 52
  • Swift 5.8 is introducing `StaticBigInt` [SE-0368](https://github.com/apple/swift-evolution/blob/main/proposals/0368-staticbigint.md). I don't pretend to fully understand it, but the Hacking With Swift writeup suggests this will make it ["easier to add new, larger integer types in the future"](https://www.hackingwithswift.com/articles/256/whats-new-in-swift-5-8). – spconrad Mar 12 '23 at 18:57
9

I'm also working on a BigNumber library with which you can do some big number calculations. Actually the library is based on the GNU Multiple Precision (GMP) library and I wrote an Objective-C / Swift wrapper. Currently big integer mathematics, including a lot of operator overloading, is possible. A code example goes like:

var err : NSError?
var bi1 = BigInt(nr: 12468642135797531)
var bi2 = BigInt(nr: "12345678901011121314151617181920", error: &err)
var res = bi1 * bi2
println("Multiply 2 BigInts: bi1 * bi2 = \(res.toString())")

which results in:

Multiply 2 BigInts: bi1 * bi2 = 153933852140173822960829726365674325601913839520

You can find the library at: https://github.com/githotto/osxgmp

nhgrif
  • 61,578
  • 25
  • 134
  • 173
iOS-Coder
  • 1,221
  • 1
  • 16
  • 28
  • Can it be used in app submitted to Appstore? I guess it be cannot due to license restrictions. – Kirsteins Jan 12 '15 at 11:17
  • I'm not an expert in GNU- and AppStore-licence/restrictions, but IMHO as long as you keep the included references intact, such that the original authors can be identified, it should be no problem. By the way I'm happy to hear that the library is of use to you! Maybe you can share with us for what purposes it is used?! – iOS-Coder Jan 13 '15 at 22:02
  • 1
    Usually the GPLs are interpreted in a way, that any software including it (compiled or linked) need to be GPL'd too. For my company this is a no-go for using any GPL'd code. This is also the opinion of our lawyers. – vikingosegundo Jul 20 '16 at 14:20
  • can it convert Data(NSData) to BigInt ? – Varun Naharia Oct 04 '17 at 08:41
  • No it can not directly convert Date(NSDate) to BigInt, but if you try something like: var date: NSDate() let dateAsInt = Int32(date.timeIntervalSince1970 * 1000) var dateAsBigInt = BitInt(nr: dateAsInt) you should probably get wat you want. I have tried this on my computer yet, but this is probably the way I would do it. Hope this helps. – iOS-Coder Oct 05 '17 at 18:50
7

I have written a big integer and big double implementation for swift, that doesn't require any additional library. Just copy it into your project. It supports whole Numbers (BInt) and Fractions (BDouble) with most of the common math operators like addition, subtraction, multiplication, exponentiation, modulus and division. Some optimized math functions like factorial or gcd are also implemented.

Here are some code examples:

// Create a new number:
let num = BInt(232)
print(num) // prints "232"

// You can also use Strings to create a number:
let veryBig = BInt("-827846184963421874362418746238453267452971345218746328715380000000000")

// Every standard math operator works well, even with normal Integers
// Visit the github page for more informations
let v0 = (BInt(5) + BInt(4)) - BInt(3)
let v1 = veryBig * 1000
let v2 = vergBig ^ num
let v3 = (veryBig ^ 50000) / (BInt(2) ^ 900) + 1
let v4 = gcd(abs(veryBig), num)

// BDouble is very similar, you can find a detailed description on Github
let fraction = BDouble("27", over: "31")
print(fraction) // prints "27/31"

You can use it freely without giving me credit, and please contribute if you want.

You can find it here: https://github.com/mkrd/Swift-Big-Integer

Marcel K.
  • 71
  • 1
  • 3
7

Here it is.

https://github.com/dankogai/swift-pons

Actually BigInt is just a part of it. In addition to BigInt you get:

  • generic Rational that takes form Int8 to BigInt as numerator and denominator
  • generic Complex that takes either integers (gaussian integers) or real number types not only Double and Float but also Rational.
  • Purely swift. Runs not only on OS X, iOS and tvOS but also Linux. Works happily in Playground.

But the best of all, it is protocol-oriented so you can extend whole integer like:

import PONS

func fib<T:POInteger>(n:T)->T { // with a little better algorithm
    if n < T(2) { return n }
    var (a, b) = (T(0), T(1))
    for _ in 2...n {
        (a, b) = (b, a+b)
    }
    return b
}

let F11 = fib(11 as Int8)
let F13 = fib(13 as UInt8)
let F23 = fib(23 as Int16)
let F24 = fib(24 as UInt16)
let F46 = fib(46 as Int32)
let F47 = fib(47 as UInt32)
let F92 = fib(92 as Int64)
let F93 = fib(93 as UInt64)
let F666 = fib(666 as BigInt)

Dan the Number Generator

dankogai
  • 1,627
  • 12
  • 7
5

I wrote library that allows you to work with big integers in Swift. In similar manner like Java's BigInteger. There are also operator overloads to make work more convenient. Example:

let a = BigInteger("111111111111111111111111111111111111111111111110000000001")!
let b = 999_999_999
let c = a + b // 111111111111111111111111111111111111111111111111000000000

https://github.com/kirsteins/BigInteger

Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • 1
    Does this also work on iOS for arm64? Also are there any steps on how to include this in the iOS project listed somewhere? – real 19 Jan 13 '15 at 10:24
  • 1
    Yes, it works on arm64. Here is a good guide on how to add the framework dependency https://github.com/stephencelis/SQLite.swift#installation. You can use this guide with BigInteger. – Kirsteins Jan 13 '15 at 10:51
  • Thanks, I trying following the steps you suggested , but I am unable to import it in my code after adding it. Could you record a video or list the steps with screenshots? – real 19 Jan 13 '15 at 17:12
  • Take a not that you have to build the framework either separately or by by building the app in order for syntax highlighting to work. Will try to record a video when I have some time. – Kirsteins Jan 13 '15 at 17:56
  • @Kirsteins How to covert Data into BigInteger using your library ? – Varun Naharia Sep 29 '17 at 06:26