Last active
June 9, 2019 18:21
-
-
Save jihuichoi/5158bd49ba69597525847a34ba34137d to your computer and use it in GitHub Desktop.
find the shortest addition chain for n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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