Skip to content

Instantly share code, notes, and snippets.

@mrklein
Created September 26, 2012 23:24
Show Gist options
  • Save mrklein/3791257 to your computer and use it in GitHub Desktop.
Save mrklein/3791257 to your computer and use it in GitHub Desktop.
Summing digits of factorials in Go
package main
import (
"fmt"
"math/big"
"strings"
"strconv"
"time"
)
func Factorial(n *big.Int) *big.Int {
var unit = big.NewInt(1)
var acc *big.Int = big.NewInt(1)
var t = n
for t.Cmp(unit) == 1 {
acc.Mul(acc, t)
t.Sub(t, unit)
}
return acc
}
func SumDigits(n string) int64 {
var r int64
l := strings.Split(n, "")
for i := 0; i < len(l); i++ {
d, _ := strconv.ParseInt(l[i], 10, 0)
r += d
}
return r
}
func main() {
var s int64 = 0
t1 := time.Now()
n := []int64{1, 12, 123, 1234, 12345, 123456}
for i := 0; i < len(n); i++ {
r := Factorial(big.NewInt(n[i]))
s += SumDigits(r.String())
}
t2 := time.Now()
fmt.Printf("Elapsed time: %v\n", t2.Sub(t1))
fmt.Println(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment