mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-30 17:28:40 +01:00
20: factorial digit sum
This commit is contained in:
@@ -0,0 +1,76 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_findFactorial(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"2",
|
||||||
|
2,
|
||||||
|
"2",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"4",
|
||||||
|
4,
|
||||||
|
"24",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"10",
|
||||||
|
10,
|
||||||
|
"3628800",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := findFactorial(tc.input)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("findFactorial=%v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_sumDigits(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"no_text",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"1",
|
||||||
|
"1",
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"12345",
|
||||||
|
"12345",
|
||||||
|
15,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"3628800",
|
||||||
|
"3628800",
|
||||||
|
27,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := sumDigits(tc.input)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("sumDigits = %d, want %d", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("sum:", sumDigits(findFactorial(100)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func findFactorial(input int) string {
|
||||||
|
product, _ := (&big.Int{}).SetString("1", 0)
|
||||||
|
for input > 0 {
|
||||||
|
i, _ := (&big.Int{}).SetString(strconv.Itoa(input), 0)
|
||||||
|
product = product.Mul(product, i)
|
||||||
|
input--
|
||||||
|
}
|
||||||
|
return product.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func sumDigits(input string) int {
|
||||||
|
l := len(input)
|
||||||
|
if l == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
sum := 0
|
||||||
|
for i := 0; i < l; i++ {
|
||||||
|
ns := input[i : i+1]
|
||||||
|
n, err := strconv.Atoi(ns)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
sum += n
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user