Skip to content

Instantly share code, notes, and snippets.

@ccw
Created December 3, 2018 01:10
Show Gist options
  • Save ccw/9e399be8295d3baddba80c197c411bc9 to your computer and use it in GitHub Desktop.
Save ccw/9e399be8295d3baddba80c197c411bc9 to your computer and use it in GitHub Desktop.
Project Euler #26 in Golang
package main
import (
"fmt"
"math/big"
"sort"
"strings"
)
func findReciprocal(s string) string {
length := len(s)
if length == 1 {
return "n/a"
}
for padding := 0; padding < 4; padding += 1 {
for i := 1; i < (length-padding)/2; i += 1 {
base := s[padding:length]
candidate := s[padding : padding+i]
x := strings.Replace(base, candidate, "", -1)
xl := len(x)
//fmt.Printf(". find %s in %s as %s\n", candidate, base, x)
if strings.Count(base, candidate) > 1 && (
xl == 0 || (xl < len(candidate) && strings.HasPrefix(candidate, x))) {
return candidate
}
}
}
return "n/a"
}
func main() {
keys := make([]int, 0)
result := make(map[int][]int)
for i := 2; i < 1000; i++ {
s := big.NewRat(1, int64(i)).FloatString(4096)
v := strings.Split(s[0:len(s)-1], ".")[1]
r := findReciprocal(v)
if r != "n/a" {
rl := len(r)
if _, ok := result[rl]; !ok {
keys = append(keys, rl)
result[rl] = []int{i}
} else {
result[rl] = append(result[rl], i)
}
}
}
sort.Ints(keys)
for _, v := range keys {
fmt.Printf("%2d -> %v\n", v, result[v])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment