I'm learning swift recently, but I have a basic problem that can't find an answer
I want to get something like
var a:Int = 3
var b:Int = 3
println( pow(a,b) ) // 27
but the pow function can work with double number only, it doesn't work with integer, and I can't even cast the int to double by something like Double(a) or a.double()...
Why it doesn't supply the power of integer? it will definitely return an integer without ambiguity ! and Why I can't cast a integer to a double? it just change 3 to 3.0 (or 3.00000... whatever)
if I got two integer and I want to do the power operation, how can I do it smoothly?
Thanks!
Sometimes, casting an
Int
to aDouble
is not a viable solution. At some magnitudes there is a loss of precision in this conversion. For example, the following code does not return what you might intuitively expect. (Swift 3.0)If you need precision at high magnitudes and don't need to worry about negative exponents — which can't be generally solved with integers anyway — then this implementation of the tail-recursive exponentiation-by-squaring algorithm is your best bet. According to this SO answer, this is "the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography."
Swift 4.x version
It turns out you can also use
pow()
. For example, you can use the following to express 10 to the 9th.Along with
pow
,powf()
returns afloat
instead of adouble
. I have only tested this on Swift 4 and macOS 10.13.mklbtz is correct about exponentiation by squaring being the standard algorithm for computing integer powers, but the tail-recursive implementation of the algorithm seems a bit confusing. See http://www.programminglogic.com/fast-exponentiation-algorithms/ for a non-recursive implementation of exponentiation by squaring in C. I've attempted to translate it to Swift here:
Of course, this could be fancied up by creating an overloaded operator to call it and it could be re-written to make it more generic so it worked on anything that implemented the
IntegerType
protocol. To make it generic, I'd probably start with something likeBut, that is probably getting carried away.
Or just :
little detail more
swift - Binary Expressions