Created
January 14, 2016 11:01
-
-
Save NathanJang/812288fa9e03c4110d10 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func gcd(x: Int, _ y: Int) -> Int { | |
var a, b: Int | |
if x > y { a = x; b = y } | |
else { a = y; b = x } | |
var remainder: Int | |
repeat { | |
remainder = a % b | |
a = b | |
b = remainder | |
} while remainder != 0 | |
return a | |
} | |
gcd(945, 2415) | |
func lcm(x: Int, _ y: Int) -> Int { | |
return x * y / gcd(x, y) | |
} | |
lcm(945, 2415) | |
infix operator ** { associativity left precedence 170 } | |
func **(base: Int, power: Int) -> Int { | |
var product = 1 | |
for _ in 0..<power { | |
product *= base | |
} | |
return product | |
} | |
let a: Int = 3, b: Int = 4 | |
a ** b | |
func representInBase(x: Int, base: Int) -> String { | |
var result = "" | |
var currentNumber = x | |
let digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] | |
if base < 1 || base >= digits.count { | |
fatalError("Base must be greater than 0 and less than \(digits.count)") | |
} | |
if currentNumber < 0 { | |
result = "-" | |
currentNumber = -currentNumber | |
} | |
var index = 0 | |
if base > 1 { | |
while base ** index <= currentNumber { | |
index += 1 | |
} | |
index -= 1 | |
while index >= 0 { | |
var digit = 0 | |
while digit * base ** index <= currentNumber { | |
digit += 1 | |
} | |
digit -= 1 | |
result += "\(digits[digit])" | |
currentNumber -= digit * base ** index | |
index -= 1 | |
} | |
} else if base == 1 { | |
for _ in 0..<currentNumber { | |
result += "1" | |
} | |
} | |
return result | |
} | |
representInBase(6253584, base: 12) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment