Skip to content

Instantly share code, notes, and snippets.

@eyesofkids
Last active March 4, 2023 15:51
Show Gist options
  • Save eyesofkids/3aaf96bf5e932f479477 to your computer and use it in GitHub Desktop.
Save eyesofkids/3aaf96bf5e932f479477 to your computer and use it in GitHub Desktop.
factorial.swift
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)
@romanlryji
Copy link

extension Int {
func fact() -> Int {
return self == 0 || self == 1 ? 1 : self * (self - 1).fact()
}
}

let t = 5.fact()

@ytyubox
Copy link

ytyubox commented Dec 11, 2019

#!/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

@arielelkin
Copy link

arielelkin commented May 18, 2021

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.

@seungjun-green
Copy link

seungjun-green commented Nov 8, 2021

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