92: Square digit chains

This commit is contained in:
VicRen
2020-12-27 17:42:49 +08:00
parent 4b3b8cbfae
commit 116e0e4f66
2 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
package main
import (
"fmt"
"strconv"
)
func main() {
count := 0
for i := 1; i < 10000000; i++ {
if goChain(i) {
count++
}
}
fmt.Println(count)
}
func goChain(n int) bool {
s := strconv.Itoa(n)
sum := 0
for _, c := range s {
i, _ := strconv.Atoi(string(c))
sum += i * i
}
if sum == 89 {
return true
} else if sum == 1 {
return false
}
return goChain(sum)
}

View File

@@ -0,0 +1,32 @@
package main
import "testing"
func Test_goChain(t *testing.T) {
type args struct {
n int
}
tests := []struct {
name string
args args
want bool
}{
{
"test1",
args{44},
false,
},
{
"test2",
args{85},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := goChain(tt.args.n); got != tt.want {
t.Errorf("goChain() = %v, want %v", got, tt.want)
}
})
}
}