BigInteger equivalent in Swift?
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?
Solution 1:
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.
Solution 2:
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.
Solution 3:
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
Solution 4:
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