I am trying calculate 2^64
with my custom-pow function.
So far I built 2 versions of it. Version 2 works.
I think version 1 should also work, but Swift crashes with an overflow error. I think It must work because I am "not" loading a higher number than I'm allowed! Why it is happening?
Version 1.0.0
func powV1(number: Int8, power: Int8) -> UInt64 {
var returnValue: UInt64 = 1
for _ in 1 ... power {
returnValue = returnValue * UInt64(number)
}
return returnValue
}
Version 2.0.0
func powV2(number: Int8, power: Int8) -> Decimal {
var returnValue: Decimal = 1
for _ in 1 ... power {
returnValue = returnValue * Decimal(number)
}
return returnValue
}
And here is call site:
powV1(number: 2, power: 64) // ← Error: OverFlow
PS: Everyone is very welcome to improve version 2.0.0
Update:
func powV1_0_1(number: Int8, power: Int8) -> UInt64 {
var returnValue: UInt64 = 1
for i in 1 ... power {
if i == power && power == 64
{
let last = Decimal(returnValue)*Decimal(number) - 1
returnValue = UInt64(last) // Error: Decimal should conform BinaryInteger says Error!?!
}
else
{
returnValue = returnValue*UInt64(number)
}
}
return returnValue
}