Skip to content

Instantly share code, notes, and snippets.

@chemacortes
Forked from costajob/fact.cr
Created July 20, 2016 09:47
Show Gist options
  • Save chemacortes/d93e9e211a1489ecb8a873a6a5f2ca48 to your computer and use it in GitHub Desktop.
Save chemacortes/d93e9e211a1489ecb8a873a6a5f2ca48 to your computer and use it in GitHub Desktop.
Factorial implementation using Big numbers in Ruby, GO and Crystal
require "big_int"
def fact(n)
return 1 if n == 0
n * fact(n - 1)
end
n = BigInt.new(ARGV[0])
puts fact(n)
package main
import (
"fmt"
"math/big"
"os"
"strconv"
)
var z, o = big.NewInt(0), big.NewInt(1)
func main() {
n, _ := strconv.Atoi(os.Args[1])
b := big.NewInt(int64(n))
fmt.Println(fact(b))
}
func fact(n *big.Int) (f *big.Int) {
if n.Cmp(z) == 0 {
f = o
} else {
var t1, t2 big.Int
f = t1.Mul(n, fact(t2.Sub(n, o)))
}
return
}
def fact(n)
return 1 if n == 0
n * fact(n - 1)
end
puts fact(ARGV[0].to_i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment