Skip to content

Instantly share code, notes, and snippets.

@jihuichoi
Last active June 9, 2019 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jihuichoi/5158bd49ba69597525847a34ba34137d to your computer and use it in GitHub Desktop.
Save jihuichoi/5158bd49ba69597525847a34ba34137d to your computer and use it in GitHub Desktop.
find the shortest addition chain for n
package main
import (
"fmt"
"sort"
)
// for play.golang.org
// https://play.golang.org/p/xJqi8EPIfSi
func main() {
n := 15
result5 := findAdditionChain(n)
fmt.Println("addition chain of ", n, " => ", result5, " - steps: ", len(result5)-1)
}
// find the shortest addition chain for n
func findAdditionChain(n int) (result []int) {
for {
if odd(n) {
if n == 1 {
break
}
n = n - 1
result = append(result, n)
} else {
n = n / 2
result = append(result, n)
}
}
sort.Ints(result)
return
}
func odd(n int) bool {
if n&0x1 == 1 {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment