Last active
March 4, 2023 15:51
-
-
Save eyesofkids/3aaf96bf5e932f479477 to your computer and use it in GitHub Desktop.
factorial.swift
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 factorial(a: Int) -> Int { | |
let n = a | |
if(n == 1){ | |
return 1 | |
}else{ | |
return n*factorial(n-1) | |
} | |
} | |
factorial(5) | |
factorial(6) | |
func factorial2(a: Int) -> Int { | |
return a == 1 ? a : a*factorial(a-1) | |
} | |
factorial2(5) | |
factorial2(6) |
The formula does not take into account that 0! == 1.
The correct algorithm is:
let n = a
if(n == 0){
return 1
} else {
return n * (n-1).factorial()
}
extension Int {
func fact() -> Int {
return self == 0 || self == 1 ? 1 : self * (self - 1).fact()
}
}
let t = 5.fact()
#!/bin/env swift
extension Int {
func factorial() -> Self? {
var tmp = self
guard tmp > 0 else {return nil}
if tmp == 0 {
return 1
}
if tmp == 1 {
return 1
}
var result = 1
while tmp > 1 {
let multipliedReport = result.multipliedReportingOverflow(by: tmp) // check overflow
if multipliedReport.overflow { // trigger early return
return nil
}
result = multipliedReport.partialValue
tmp -= 1
}
return result
}
}
Any Number great than 20, it's factorial will overflow, a.k.a. return nil
func factorial(_ num: UInt) -> UInt {
guard num != 0 else {
return 1
}
return (1...num).reduce(1, { $0 * $1 })
}
factorial(0) // 1
factorial(5) // 120
Recursion is for hipsters 😜
Note the use of UInt
, as factorials are only for positive numbers.
func factorial(_ n: Int) -> Double { return (1...n).map(Double.init).reduce(1.0, *) }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
func factorial(of: Int) -> Int
{
return (1...max(of, 1)).reduce(1, *)
}