Created
September 26, 2012 23:24
-
-
Save mrklein/3791257 to your computer and use it in GitHub Desktop.
Summing digits of factorials in Go
This file contains hidden or 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
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