34: digit factorials

This commit is contained in:
VicRen
2020-11-04 09:56:19 +08:00
parent 804b2722d1
commit 8b1bf8619f
2 changed files with 151 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
package main
import (
"fmt"
"strconv"
)
func main() {
sum := 0
max := factorialOf(9) * 10
for i := 3; i < max; i++ {
if sumNumberFactorials(splitNumber(i)) == i {
sum += i
}
}
fmt.Println("sum:", sum)
}
func sumNumberFactorials(ns []int) int {
sum := 0
for _, n := range ns {
sum += factorialOf(n)
}
return sum
}
func splitNumber(n int) []int {
var ret []int
str := strconv.Itoa(n)
for _, c := range str {
i, _ := strconv.Atoi(string(c))
ret = append(ret, i)
}
return ret
}
func factorialOf(n int) int {
p := 1
for i := n; i > 0; i-- {
p *= i
}
return p
}

View File

@@ -0,0 +1,108 @@
package main
import (
"reflect"
"testing"
)
func Test_factorialOf(t *testing.T) {
type args struct {
n int
}
tt := []struct {
name string
args args
want int
}{
{
"1",
args{1},
1,
},
{
"2",
args{2},
2,
},
{
"4",
args{4},
24,
},
{
"10",
args{10},
3628800,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if got := factorialOf(tc.args.n); got != tc.want {
t.Errorf("factorialOf() = %v, want %v", got, tc.want)
}
})
}
}
func Test_splitNumber(t *testing.T) {
type args struct {
n int
}
tt := []struct {
name string
args args
want []int
}{
{
"13",
args{13},
[]int{1, 3},
},
{
"123",
args{123},
[]int{1, 2, 3},
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if got := splitNumber(tc.args.n); !reflect.DeepEqual(got, tc.want) {
t.Errorf("splitNumber() = %v, want %v", got, tc.want)
}
})
}
}
func Test_sumNumberFactorials(t *testing.T) {
type args struct {
ns []int
}
tt := []struct {
name string
args args
want int
}{
{
"1",
args{[]int{1}},
1,
},
{
"12",
args{[]int{1, 2}},
3,
},
{
"123",
args{[]int{1, 2, 3}},
9,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if got := sumNumberFactorials(tc.args.ns); got != tc.want {
t.Errorf("sumNumberFactorials() = %v, want %v", got, tc.want)
}
})
}
}