How to get the Power of some Integer in Swift language?

Related searches

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!

If you like, you could declare an infix operator to do it.

// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8

I used two carets so you can still use the XOR operator.

Update for Swift 3

In Swift 3 the "magic number" precedence is replaced by precedencegroups:

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8

How to get the Power of some Integer in Swift language?, 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 � In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size: On a 32-bit platform, Int is the same size as Int32. On a 64-bit platform, Int is the same size as Int64.

Other than that your variable declarations have syntax errors, this works exactly how you expected it to. All you have to do is cast a and b to Double and pass the values to pow. Then, if you're working with 2 Ints and you want an Int back on the other side of the operation, just cast back to Int.

import Darwin 

let a: Int = 3
let b: Int = 3

let x: Int = Int(pow(Double(a),Double(b)))

[SOLVED] How to get the Power of some Integer in Swift language , If you like, you could declare an infix operator to do it. // Put this at file level anywhere in your project infix operator ^^ { associativity left precedence 160 } func� j'apprends swift récemment, mais j'ai un problème de base qui ne trouve pas de réponse . je veux quelque chose comme . var a:Int = 3 var b:Int = 3 println( pow(a,b) ) // 27

Sometimes, casting an Int to a Double 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.

Double(Int.max - 1) < Double(Int.max) // false!

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."

// using Swift 5.0
func pow<T: BinaryInteger>(_ base: T, _ power: T) -> T {
    func expBySq(_ y: T, _ x: T, _ n: T) -> T {
        precondition(n >= 0)
        if n == 0 {
            return y
        } else if n == 1 {
            return y * x
        } else if n.isMultiple(of: 2) {
            return expBySq(y, x * x, n / 2)
        } else { // n is odd
            return expBySq(y * x, x * x, (n - 1) / 2)
        }
    }

    return expBySq(1, base, power) 
}

Note: in this example I've used a generic T: BinaryInteger. This is so you can use Int or UInt or any other integer-like type.

How to get the 'pow()' function in the Swift programming language , The pow() returns double value. � var q = pow(number, power) // in this one should be in decimal form � In case to work for integer: � var q =Int(pow(Double( number),� Enumerations in Swift are much more flexible, and don’t have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

If you really want an 'Int only' implementation and don't want to coerce to/from Double, you'll need to implement it. Here is a trivial implementation; there are faster algorithms but this will work:

func pow (_ base:Int, _ power:UInt) -> Int {
  var answer : Int = 1
  for _ in 0..<power { answer *= base }
  return answer
}

> pow (2, 4)
$R3: Int = 16
> pow (2, 8)
$R4: Int = 256
> pow (3,3)
$R5: Int = 27

In a real implementation you'd probably want some error checking.

Int power function in Swift 3, In fact, I wanted to add an integer power operator as : importing Foundation into Swift 3, NSDecimal has become Decimal, and some global functions such as : This enumeration, called Kind, expresses the kind of number that a particular integer represents. Specifically, it expresses whether the number is negative, zero, or positive. This example also adds a new computed instance property to Int, called kind, which returns the appropriate Kind enumeration case for that integer.

little detail more

   infix operator ^^ { associativity left precedence 160 }
   func ^^ (radix: Int, power: Int) -> Int {
       return Int(pow(CGFloat(radix), CGFloat(power)))
   }

swift - Binary Expressions

pow(_:_:), Returns a decimal number raised to a given power. Availability. iOS 7.0+; macOS 10.9+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+; Xcode 7.1+. Framework. The program below takes two integers from the user (a base number and an exponent) and calculates the power. For example: In the case of 2 3 . 2 is the base number

The first parameter is called mathFunction, and is of type (Int, Int)-> Int. You can pass any function of that type as the argument for this first parameter. The second and third parameters are called a and b, and are both of type Int. These are used as the two input values for the provided math function.

The pow () function computes a base number raised to the power of exponent number. This function is defined in <cmath> header file. [Mathematics] base exponent = pow (base, exponent) [C++ Programming] pow () Prototype [As of C++ 11 standard]

Returns the base-10 logarithm of a number. Number.Mod: Divides two numbers and returns the remainder of the resulting number. Number.Permutations: Returns the number of total permutatons of a given number of items for the optional permutation size. Number.Power: Returns a number raised by a power. Number.Sign

Comments
  • These type declarations are wrong
  • most languages don't have an integer power function due to this reason
  • @phuclv's note points to a great discussion on the topic. I would change the text in the link to "these reasons"
  • So if you wanted to do this for Floats, would you do this: infix operator ^^ { } func ^^ (radix: Float, power: Float) -> Float { return Float(pow(Double(radix), Double(power))) }
  • func ^^ (radix: Double, power: Double) -> Double { return Double(pow(Double(radix), Double(power))) }
  • I found this didn't quite behave as I expected because the precedence was off. For an exponentiative operator, set precedence to 160 (see developer.apple.com/library/ios/documentation/Swift/Conceptual/… and developer.apple.com/library/ios/documentation/Swift/Conceptual/…) like so: infix operator ^^ { precedence 160 } func ^^... and so on
  • I really like this solution, but with Swift 3 it does not work. Any idea how to make it work?
  • func p(_ b: Bool) -> Double { return b?-1:1 } ?
  • This answer is the clearest with Double and Int types.
  • That is what I want, thanks. In Python, just 3 ** 3. Sometimes, I need to solve algorithm problem using Swift, it is really painful comparing to using Python.
  • And of course you can always define this as an operator (as the more popular answers suggest) or an extension to Int or you can have those things call this free function — whatever your heart desires.