Created
October 14, 2017 17:53
-
-
Save md2perpe/908e62b8e8d10ccc0e5206181b6752a9 to your computer and use it in GitHub Desktop.
Kaprekar's constant
This file contains hidden or 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
// https://en.wikipedia.org/wiki/6174_(number) | |
package main | |
import ( | |
"fmt" | |
"sort" | |
"strconv" | |
) | |
type ByteSlice []byte | |
func (bs ByteSlice) Len() int { | |
return len(bs) | |
} | |
func (bs ByteSlice) Less(i, j int) bool { | |
return bs[i] < bs[j] | |
} | |
func (bs ByteSlice) Swap(i, j int) { | |
bs[i], bs[j] = bs[j], bs[i] | |
} | |
func main() { | |
for n := 1100; n < 1120; n++ { | |
fmt.Printf("%4d:\n", n) | |
m := n | |
for i := 0; i < 100; i++ { | |
if m == 0 { | |
break | |
} | |
s := strconv.Itoa(m) | |
bs := ByteSlice([]byte(s)) | |
sort.Sort(bs) | |
m_lo, err := strconv.Atoi(string(bs)) | |
if err != nil { | |
panic(err) | |
} | |
sort.Sort(sort.Reverse(bs)) | |
m_hi, err := strconv.Atoi(string(bs)) | |
if err != nil { | |
panic(err) | |
} | |
for m_hi < 1000 { | |
m_hi *= 10 | |
} | |
m_old := m | |
m = m_hi - m_lo | |
if m == m_old { | |
break | |
} | |
fmt.Printf(" %4d - %4d = %4d\n", m_hi, m_lo, m) | |
} | |
fmt.Printf("\n") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment