Skip to content

Instantly share code, notes, and snippets.

@thecoolwinter
Last active May 1, 2025 20:47
Show Gist options
  • Save thecoolwinter/21ba42c9c8dc709e8954e4a623a184ed to your computer and use it in GitHub Desktop.
Save thecoolwinter/21ba42c9c8dc709e8954e4a623a184ed to your computer and use it in GitHub Desktop.
A fast, simple, integer power function for Swift. By default Swift does not ship with a `pow` function that takes two `Int` arguments.
//
// IntPow.swift
//
// Created by Khan Winter on 5/1/25.
//
/// Raises an integer to a positive power.
@inlinable
public func pow(_ base: Int, _ exp: UInt) -> Int {
var exp = exp
var base = base
var result = 1
repeat {
if exp & 1 != 0 {
result *= base
}
exp >>= 1
base *= base
} while exp != 0
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment