26: reciprocal cycles

This commit is contained in:
VicRen
2020-10-26 11:13:58 +08:00
parent 117fc7ab5f
commit 0b3b448000
2 changed files with 89 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
package main
import "fmt"
func main() {
max := 0
d := 1
for d < 1000 {
n := findCycleLengthOfOneNth(d)
if n > max {
max = d
}
d++
}
fmt.Println("max:", max)
}
func findCycleLengthOfOneNth(n int) int {
m := map[int]int{}
a := 1
t := 0
for {
if _, ok := m[a]; ok {
break
}
m[a] = t
a = a % n * 10
if a == 0 {
return t
}
t++
}
return t - m[a]
}

View File

@@ -0,0 +1,55 @@
package main
import (
"reflect"
"testing"
)
func Test_findDecimalOfOneNth(t *testing.T) {
type args struct {
n int
}
tt := []struct {
name string
args args
want int
}{
{
"2",
args{2},
1,
},
{
"4",
args{4},
2,
},
{
"6",
args{6},
1,
},
{
"7",
args{7},
6,
},
{
"10",
args{10},
1,
},
{
"100",
args{100},
2,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if got := findCycleLengthOfOneNth(tc.args.n); !reflect.DeepEqual(got, tc.want) {
t.Errorf("findCycleLengthOfOneNth() = %v, want %v", got, tc.want)
}
})
}
}