问题
I'm not a programmer, I just like to write some code in my free time! I used to program in python3, now I'm trying to learn apple's Swift. My problem:
in python3 I used without problems really huge numbers like 10**1000, I can print them, do math operations with them, and so on. In Swift, I can not do the same, because starting from 10**300 or 10**400, both Double and Float type gives "+infinity" as result, so I can not print it, nor do any operation with it...
How can I solve this? (PS. If anyone is interested, I'm trying to do some ProjectEuler's problems! http://projecteuler.net) Thank you in advance, and sorry for any mistake I could have maid, I'm not english, and it's my first time on StackOverflow!
回答1:
I'm working on a BigNumber library with which you can do some HUGE 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
I hope the library (see: https://github.com/githotto/osxgmp) may be useful for you.
回答2:
If you know (or willing to learn) how to implement a bignumber, define your own type in swift (presumably as a struct), then implement overloads of the arithmetic operators +, -, etc. and whatever else you need to work with those big numbers.
There's an implementation in C++ here, but if you google a little bit you might find other algorithms that you can translate into swift code, or examples in other languages (if you're not familiar with C++)
Swift already defines 2 "extended" floating point types named Float80
and Float96
:
Float80 80 bit MacOS float: 1 sign bit, 15 exponent bits, 1 integer bit, 63 fraction bits
Float96 96 bit 68881 float: 1 sign bit, 15 exponent bits, 16 pad bits, 1 integer bit, 63 fraction bits
but apparently no operator overload is defined - they are just "isolated" structs.
来源:https://stackoverflow.com/questions/25471876/use-huge-numbers-in-apple-swift