Skip to content

Instantly share code, notes, and snippets.

@jmdeldin
Last active December 28, 2015 05:56
Show Gist options
  • Save jmdeldin/50a0b51c1e675e7141ef to your computer and use it in GitHub Desktop.
Save jmdeldin/50a0b51c1e675e7141ef to your computer and use it in GitHub Desktop.
Generating lots of numbers for the 196 palindrome quest.

Prerequisites

On Ubuntu:

sudo aptitude install golang libgmp3-dev
mkdir -p ~/src/gopath
echo 'EXPORT GOPATH=~/src/gopath' >> ~/.bashrc
source ~/.bashrc
go get github.com/ncw/gmp

Usage

Copy this file to a new directory and run it:

go build lychrel.go
./lychrel > lychrel.log

The program will output the number of iterations to the screen (STDERR) and the number to STDOUT (which we're redirecting to a file).

In another terminal, monitor the length of the numbers with

watch 'tail -1 lychrel.log | wc -c`
package main
import (
"fmt"
"os"
// "math/big"
// use the gmp library -- aptitude install libgmp3-dev
big "github.com/ncw/gmp"
"unicode/utf8"
)
// https://github.com/golang/example/blob/master/stringutil/reverse.go
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func step(n *big.Int) *big.Int {
rev := new(big.Int)
rev.SetString(Reverse(n.String()), 10)
return n.Add(n, rev)
}
func length(n *big.Int) int {
return utf8.RuneCountInString(n.String())
}
func main() {
i := 0
n := big.NewInt(196)
for {
n = step(n)
if i % 10000 == 0 {
os.Stderr.WriteString(fmt.Sprintf("%d\n", i))
fmt.Println(n)
}
i += 1
}
}
import Debug.Trace
numDigits :: Integer -> Int
numDigits n = length (show n)
reverseInt :: Integer -> Integer
reverseInt x = read . reverse . show $ x
step n = n + reverseInt n
-- this is the number we stop on
solve n 200 = n
solve n startingI =
if startingI `mod` 1000 == 0 then
trace ("step " ++ show startingI ++ ": " ++ (show . numDigits $ n))
innerSolve (step n) startingI
else
innerSolve (step n) startingI
innerSolve n i = solve n (succ i)
-- use this like so
-- :l lychrel
-- solve 196 0
// javac Lychrel.java && java Lychrel
import java.math.BigInteger;
public class Lychrel {
public static BigInteger reverse(BigInteger n) {
String str = new StringBuilder(n.toString()).reverse().toString();
return new BigInteger(str);
}
public static BigInteger step(BigInteger n) {
return n.add(reverse(n));
}
public static void main(String[] argv) {
BigInteger n = BigInteger.valueOf(196);
int i = 0;
while (true) {
n = step(n);
if (i % 10000 == 0) {
System.out.println(n);
}
i += 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment