WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bilinear interpolation




Go: package main

import (
	"image"
	"image/color"
	"image/jpeg"
	"log"
	"math"
	"os"

	"golang.org/x/image/draw"
)

func scale(dst draw.Image, src image.Image) {
	sr := src.Bounds()
	dr := dst.Bounds()
	mx := float64(sr.Dx()-1) / float64(dr.Dx())
	my := float64(sr.Dy()-1) / float64(dr.Dy())
	for x := dr.Min.X; x < dr.Max.X; x++ {
		for y := dr.Min.Y; y < dr.Max.Y; y++ {
			gx, tx := math.Modf(float64(x) * mx)
			gy, ty := math.Modf(float64(y) * my)
			srcX, srcY := int(gx), int(gy)
			r00, g00, b00, a00 := src.At(srcX, srcY).RGBA()
			r10, g10, b10, a10 := src.At(srcX+1, srcY).RGBA()
			r01, g01, b01, a01 := src.At(srcX, srcY+1).RGBA()
			r11, g11, b11, a11 := src.At(srcX+1, srcY+1).RGBA()
			result := color.RGBA64{
				R: blerp(r00, r10, r01, r11, tx, ty),
				G: blerp(g00, g10, g01, g11, tx, ty),
				B: blerp(b00, b10, b01, b11, tx, ty),
				A: blerp(a00, a10, a01, a11, tx, ty),
			}
			dst.Set(x, y, result)
		}
	}
}

func lerp(s, e, t float64) float64 { return s + (e-s)*t }
func blerp(c00, c10, c01, c11 uint32, tx, ty float64) uint16 {
	return uint16(lerp(
		lerp(float64(c00), float64(c10), tx),
		lerp(float64(c01), float64(c11), tx),
		ty,
	))
}

func main() {
	src, err := readImage("Lenna100.jpg")
	if err != nil {
		log.Fatal(err)
	}
	sr := src.Bounds()
	dr := image.Rect(0, 0, sr.Dx()*16/10, sr.Dy()*16/10)
	dst := image.NewRGBA(dr)

	
	scale(dst, src)
	err = writeJPEG(dst, "Lenna100_larger.jpg")
	if err != nil {
		log.Fatal(err)
	}

	
	
	draw.BiLinear.Scale(dst, dr, src, sr, draw.Src, nil)
	err = writeJPEG(dst, "Lenna100_larger.draw.jpg")
	if err != nil {
		log.Fatal(err)
	}
}

func readImage(filename string) (image.Image, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close() 
	m, _, err := image.Decode(f)
	return m, err
}

func writeJPEG(m image.Image, filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	err = jpeg.Encode(f, m, nil)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	return err
}
Task: Vector




Go: package main

import "fmt"

type vector []float64

func (v vector) add(v2 vector) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi + v2[i]
    }
    return r
}

func (v vector) sub(v2 vector) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi - v2[i]
    }
    return r
}

func (v vector) scalarMul(s float64) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi * s
    }
    return r
}

func (v vector) scalarDiv(s float64) vector {
    r := make([]float64, len(v))
    for i, vi := range v {
        r[i] = vi / s
    }
    return r
}

func main() {
    v1 := vector{5, 7}
    v2 := vector{2, 3}
    fmt.Println(v1.add(v2))
    fmt.Println(v1.sub(v2))
    fmt.Println(v1.scalarMul(11))
    fmt.Println(v1.scalarDiv(2))
}
Task: Elliptic curve arithmetic




Go: package main

import (
    "fmt"
    "math"
)

const bCoeff = 7

type pt struct{ x, y float64 }

func zero() pt {
    return pt{math.Inf(1), math.Inf(1)}
}

func is_zero(p pt) bool {
    return p.x > 1e20 || p.x < -1e20
}

func neg(p pt) pt {
    return pt{p.x, -p.y}
}

func dbl(p pt) pt {
    if is_zero(p) {
        return p
    }
    L := (3 * p.x * p.x) / (2 * p.y)
    x := L*L - 2*p.x
    return pt{
        x: x,
        y: L*(p.x-x) - p.y,
    }
}

func add(p, q pt) pt {
    if p.x == q.x && p.y == q.y {
        return dbl(p)
    }
    if is_zero(p) {
        return q
    }
    if is_zero(q) {
        return p
    }
    L := (q.y - p.y) / (q.x - p.x)
    x := L*L - p.x - q.x
    return pt{
        x: x,
        y: L*(p.x-x) - p.y,
    }
}

func mul(p pt, n int) pt {
    r := zero()
    for i := 1; i <= n; i <<= 1 {
        if i&n != 0 {
            r = add(r, p)
        }
        p = dbl(p)
    }
    return r
}

func show(s string, p pt) {
    fmt.Printf("%s", s)
    if is_zero(p) {
        fmt.Println("Zero")
    } else {
        fmt.Printf("(%.3f, %.3f)\n", p.x, p.y)
    }
}

func from_y(y float64) pt {
    return pt{
        x: math.Cbrt(y*y - bCoeff),
        y: y,
    }
}
    
func main() {
    a := from_y(1)
    b := from_y(2)
    show("a = ", a)
    show("b = ", b)
    c := add(a, b)
    show("c = a + b = ", c)
    d := neg(c)
    show("d = -c = ", d)
    show("c + d = ", add(c, d))
    show("a + b + d = ", add(a, add(b, d)))
    show("a * 12345 = ", mul(a, 12345))
}
Task: Chebyshev coefficients




Go: package main

import (
    "fmt"
    "math"
)

type cheb struct {
    c        []float64
    min, max float64
}

func main() {
    fn := math.Cos
    c := newCheb(0, 1, 10, 10, fn)
    fmt.Println("coefficients:")
    for _, c := range c.c {
        fmt.Printf("% .15f\n", c)
    }
    fmt.Println("\nx     computed    approximated    computed-approx")
    const n = 10
    for i := 0.; i <= n; i++ {
        x := (c.min*(n-i) + c.max*i) / n
        computed := fn(x)
        approx := c.eval(x)
        fmt.Printf("%.1f %12.8f  %12.8f   % .3e\n",
            x, computed, approx, computed-approx)
    }
}

func newCheb(min, max float64, nCoeff, nNodes int, fn func(float64) float64) *cheb {
    c := &cheb{
        c:   make([]float64, nCoeff),
        min: min,
        max: max,
    }
    f := make([]float64, nNodes)
    p := make([]float64, nNodes)
    z := .5 * (max + min)
    r := .5 * (max - min)
    for k := 0; k < nNodes; k++ {
        p[k] = math.Pi * (float64(k) + .5) / float64(nNodes)
        f[k] = fn(z + math.Cos(p[k])*r)
    }
    n2 := 2 / float64(nNodes)
    for j := 0; j < nCoeff; j++ {
        sum := 0.
        for k := 0; k < nNodes; k++ {
            sum += f[k] * math.Cos(float64(j)*p[k])
        }
        c.c[j] = sum * n2
    }
    return c
}

func (c *cheb) eval(x float64) float64 {
    x1 := (2*x - c.min - c.max) / (c.max - c.min)
    x2 := 2 * x1
    var s, t float64
    for j := len(c.c) - 1; j >= 1; j-- {
        t, s = x2*t-s+c.c[j], t
    }
    return x1*t - s + .5*c.c[0]
}
Task: Burrows–Wheeler transform




Go: package main

import (
    "fmt"
    "sort"
    "strings"
)

const stx = "\002"
const etx = "\003"

func bwt(s string) (string, error) {
    if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 {
        return "", fmt.Errorf("String can't contain STX or ETX")
    }
    s = stx + s + etx
    le := len(s)
    table := make([]string, le)
    table[0] = s
    for i := 1; i < le; i++ {
        table[i] = s[i:] + s[:i]
    }
    sort.Strings(table)
    lastBytes := make([]byte, le)
    for i := 0; i < le; i++ {
        lastBytes[i] = table[i][le-1]
    }
    return string(lastBytes), nil
}

func ibwt(r string) string {
    le := len(r)
    table := make([]string, le)
    for range table {
        for i := 0; i < le; i++ {
            table[i] = r[i:i+1] + table[i]
        }
        sort.Strings(table)
    }
    for _, row := range table {
        if strings.HasSuffix(row, etx) {
            return row[1 : le-1]
        }
    }
    return ""
}

func makePrintable(s string) string {
    
    t := strings.Replace(s, stx, "^", 1)
    return strings.Replace(t, etx, "|", 1)
}

func main() {
    tests := []string{
        "banana",
        "appellee",
        "dogwood",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "\002ABC\003",
    }
    for _, test := range tests {
        fmt.Println(makePrintable(test))
        fmt.Print(" --> ")
        t, err := bwt(test)
        if err != nil {
            fmt.Println("ERROR:", err)
        } else {
            fmt.Println(makePrintable(t))
        }
        r := ibwt(t)
        fmt.Println(" -->", r, "\n")
    }
}
Task: Card shuffles




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func reverse(s []int) {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
}

func riffle(deck []int, iterations int) []int {
    le := len(deck)
    pile := make([]int, le)
    copy(pile, deck)
    for i := 0; i < iterations; i++ {
        mid := le / 2
        tenpc := mid / 10
        
        cut := mid - tenpc + rand.Intn(2*tenpc+1)
        
        deck1 := make([]int, cut)
        deck2 := make([]int, le-cut)
        copy(deck1, pile[:cut])
        copy(deck2, pile[cut:])
        pile = pile[:0]
        fromTop := rand.Intn(2) 
        for len(deck1) > 0 && len(deck2) > 0 {
            if fromTop == 1 {
                el1 := deck1[0]
                deck1 = deck1[1:]
                el2 := deck2[0]
                deck2 = deck2[1:]
                pile = append(pile, el1, el2)
            } else {
                el1 := deck1[len(deck1)-1]
                deck1 = deck1[:len(deck1)-1]
                el2 := deck2[len(deck2)-1]
                deck2 = deck2[:len(deck2)-1]
                pile = append(pile, el1, el2)
            }
        }
        
        if len(deck1) > 0 {
            pile = append(pile, deck1...)
        } else if len(deck2) > 0 {
            pile = append(pile, deck2...)
        }
        reverse(pile) 
    }
    return pile
}

func overhand(deck []int, iterations int) []int {
    le := len(deck)
    pile := make([]int, le)
    copy(pile, deck)
    pile2 := make([]int, 0)
    twentypc := le / 5
    for i := 0; i < iterations; i++ {
        for len(pile) > 0 {
            cards := 1 + rand.Intn(twentypc)
            if cards > len(pile) {
                cards = len(pile)
            }
            temp := make([]int, cards)
            copy(temp, pile[:cards])
            pile2 = append(temp, pile2...)
            pile = pile[cards:]
        }
        pile = append(pile, pile2...)
        pile2 = pile2[:0]
    }
    return pile
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println("Starting deck:")
    deck := make([]int, 20)
    for i := 0; i < 20; i++ {
        deck[i] = i + 1
    }
    fmt.Println(deck)
    const iterations = 10
    fmt.Println("\nRiffle shuffle with", iterations, "iterations:")
    fmt.Println(riffle(deck, iterations))
    fmt.Println("\nOverhand shuffle with", iterations, "iterations:")
    fmt.Println(overhand(deck, iterations))
    fmt.Println("\nStandard library shuffle with 1 iteration:")
    rand.Shuffle(len(deck), func(i, j int) {
        deck[i], deck[j] = deck[j], deck[i] 
    })
    fmt.Println(deck)
}
Task: Faulhaber's triangle




Go: package main

import (
    "fmt"
    "math/big"
)

func bernoulli(n uint) *big.Rat {
    a := make([]big.Rat, n+1)
    z := new(big.Rat)
    for m := range a {
        a[m].SetFrac64(1, int64(m+1))
        for j := m; j >= 1; j-- {
            d := &a[j-1]
            d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
        }
    }
    
    if n != 1 {
        return &a[0]
    }
    a[0].Neg(&a[0])
    return &a[0]
}

func binomial(n, k int) int64 {
    if n <= 0 || k <= 0 || n < k {
        return 1
    }
    var num, den int64 = 1, 1
    for i := k + 1; i <= n; i++ {
        num *= int64(i)
    }
    for i := 2; i <= n-k; i++ {
        den *= int64(i)
    }
    return num / den
}

func faulhaberTriangle(p int) []big.Rat {
    coeffs := make([]big.Rat, p+1)
    q := big.NewRat(1, int64(p)+1)
    t := new(big.Rat)
    u := new(big.Rat)
    sign := -1
    for j := range coeffs {
        sign *= -1
        d := &coeffs[p-j]
        t.SetInt64(int64(sign))
        u.SetInt64(binomial(p+1, j))
        d.Mul(q, t)
        d.Mul(d, u)
        d.Mul(d, bernoulli(uint(j)))
    }
    return coeffs
}

func main() {
    for i := 0; i < 10; i++ {
        coeffs := faulhaberTriangle(i)
        for _, coeff := range coeffs {
            fmt.Printf("%5s  ", coeff.RatString())
        }
        fmt.Println()
    }
    fmt.Println()
    
    k := 17
    cc := faulhaberTriangle(k)
    n := int64(1000)
    nn := big.NewRat(n, 1)
    np := big.NewRat(1, 1)
    sum := new(big.Rat)
    tmp := new(big.Rat)
    for _, c := range cc {
        np.Mul(np, nn)
        tmp.Set(np)
        tmp.Mul(tmp, &c)
        sum.Add(sum, tmp)
    }
    fmt.Println(sum.RatString())
}
Task: Paraffins




Go: package main

import (
    "fmt"
    "math/big"
)

const branches = 4
const nMax = 500

var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)

func tree(br, n, l, sum int, cnt *big.Int) {
    for b := br + 1; b <= branches; b++ {
        sum += n
        if sum > nMax {
            return
        }
        if l*2 >= sum && b >= branches {
            return
        }
        if b == br+1 {
            c[br].Mul(&rooted[n], cnt)
        } else {
            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
            c[br].Mul(&c[br], tmp)
            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
        }
        if l*2 < sum {
            unrooted[sum].Add(&unrooted[sum], &c[br])
        }
        if b < branches {
            rooted[sum].Add(&rooted[sum], &c[br])
        }
        for m := n - 1; m > 0; m-- {
            tree(b, m, l, sum, &c[br])
        }
    }
}

func bicenter(s int) {
    if s&1 == 0 {
        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
        unrooted[s].Add(&unrooted[s], tmp)
    }
}

func main() {
    rooted[0].SetInt64(1)
    rooted[1].SetInt64(1)
    unrooted[0].SetInt64(1)
    unrooted[1].SetInt64(1)
    for n := 1; n <= nMax; n++ {
        tree(0, n, n, 1, big.NewInt(1))
        bicenter(n)
        fmt.Printf("%d: %d\n", n, &unrooted[n])
    }
}
Task: Faulhaber's formula




Go: package main

import (
	"fmt"
	"math/big"
)

func bernoulli(z *big.Rat, n int64) *big.Rat {
	if z == nil {
		z = new(big.Rat)
	}
	a := make([]big.Rat, n+1)
	for m := range a {
		a[m].SetFrac64(1, int64(m+1))
		for j := m; j >= 1; j-- {
			d := &a[j-1]
			d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
		}
	}
	return z.Set(&a[0])
}

func main() {
	
	q := new(big.Rat)
	c := new(big.Rat)      
	be := new(big.Rat)     
	bi := big.NewRat(1, 1) 

	for p := int64(0); p < 10; p++ {
		fmt.Print(p, " : ")
		q.SetFrac64(1, p+1)
		neg := true
		for j := int64(0); j <= p; j++ {
			neg = !neg
			if neg {
				c.Neg(q)
			} else {
				c.Set(q)
			}
			bi.Num().Binomial(p+1, j)
			bernoulli(be, j)
			c.Mul(c, bi)
			c.Mul(c, be)
			if c.Num().BitLen() == 0 {
				continue
			}
			if j == 0 {
				fmt.Printf(" %4s", c.RatString())
			} else {
				fmt.Printf(" %+2d/%-2d", c.Num(), c.Denom())
			}
			fmt.Print("×n")
			if exp := p + 1 - j; exp > 1 {
				fmt.Printf("^%-2d", exp)
			}
		}
		fmt.Println()
	}
}
Task: Active Directory_Search for a user




Go: package main

import (
    "log"
    "github.com/jtblin/go-ldap-client"
)

func main() {
    client := &ldap.LDAPClient{
        Base:        "dc=example,dc=com",
        Host:        "ldap.example.com",
        Port:        389,
        GroupFilter: "(memberUid=%s)",
    }
    defer client.Close()
    err := client.Connect()
    if err != nil { 
        log.Fatalf("Failed to connect : %+v", err)
    }
    groups, err := client.GetGroupsOfUser("username")
    if err != nil {
        log.Fatalf("Error getting groups for user %s: %+v", "username", err)
    }
    log.Printf("Groups: %+v", groups) 
}
Task: Prime conspiracy




Go: package main

import (
	"fmt"
	"sort"
)

func sieve(limit uint64) []bool {
	limit++
	
	
	c := make([]bool, limit)
	c[0] = true
	c[1] = true
	p := uint64(3) 
	for {
		p2 := p * p
		if p2 >= limit {
			break
		}
		for i := p2; i < limit; i += 2 * p {
			c[i] = true
		}
		for {
			p += 2
			if !c[p] {
				break
			}
		}
	}
	return c
}

func main() {
	
	sieved := sieve(2038074743)

	transMap := make(map[int]int, 19)
	i := 2            
	p := int64(3 - 2) 
	n := 1
	for _, num := range [...]int{1e4, 1e6, 1e8} {
		for ; n < num; n++ {
			
			p += 2
			for sieved[p] {
				p += 2
			}
			
			j := int(p % 10)
			transMap[i*10+j]++
			i = j
		}
		reportTransitions(transMap, n)
	}
}

func reportTransitions(transMap map[int]int, num int) {
	keys := make([]int, 0, len(transMap))
	for k := range transMap {
		keys = append(keys, k)
	}
	sort.Ints(keys)
	fmt.Println("First", num, "primes. Transitions prime % 10 -> next-prime % 10.")
	for _, key := range keys {
		count := transMap[key]
		freq := float64(count) / float64(num) * 100
		fmt.Printf("%d -> %d  count: %7d", key/10, key%10, count)
		fmt.Printf("  frequency: %4.2f%%\n", freq)
	}
	fmt.Println()
}
Task: List rooted trees




Go: package main

import (
    "fmt"
    "log"
    "os"
    "strconv"
)

type tree uint64

var (
    list   []tree
    offset = [32]uint{1: 1}
)

func add(t tree) {
    list = append(list, 1|t<<1)
}

func show(t tree, l uint) {
    for ; l > 0; t >>= 1 {
        l--
        var paren byte
        if (t & 1) != 0 {
            paren = '('
        } else {
            paren = ')'
        }
        fmt.Printf("%c", paren)
    }
}

func listTrees(n uint) {
    for i := offset[n]; i < offset[n+1]; i++ {
        show(list[i], n*2)
        fmt.Println()
    }
}



func assemble(n uint, t tree, sl, pos, rem uint) {
    if rem == 0 {
        add(t)
        return
    }

    if sl > rem { 
        sl = rem
        pos = offset[sl]
    } else if pos >= offset[sl+1] {
        
        sl--
        if sl == 0 {
            return
        }
        pos = offset[sl]
    }

    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
    assemble(n, t, sl, pos+1, rem)
}

func mktrees(n uint) {
    if offset[n+1] > 0 {
        return
    }
    if n > 0 {
        mktrees(n - 1)
    }

    assemble(n, 0, n-1, offset[n-1], n-1)
    offset[n+1] = uint(len(list))
}

func main() {
    if len(os.Args) != 2 {
        log.Fatal("There must be exactly 1 command line argument")
    }
    n, err := strconv.Atoi(os.Args[1])
    if err != nil {
        log.Fatal("Argument is not a valid number")
    }
    if n <= 0 || n > 19 { 
        n = 5
    }
    
    add(0)

    mktrees(uint(n))
    fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
    listTrees(uint(n))
}
Task: Elementary cellular automaton_Random number generator




Go: package main

import "fmt"

const n = 64

func pow2(x uint) uint64 {
    return uint64(1) << x
}

func evolve(state uint64, rule int) {
    for p := 0; p < 10; p++ {
        b := uint64(0)
        for q := 7; q >= 0; q-- {
            st := state
            b |= (st & 1) << uint(q)
            state = 0
            for i := uint(0); i < n; i++ {
                var t1, t2, t3 uint64
                if i > 0 {
                    t1 = st >> (i - 1)
                } else {
                    t1 = st >> 63
                }
                if i == 0 {
                    t2 = st << 1
                } else if i == 1 {
                    t2 = st << 63

                } else {
                    t2 = st << (n + 1 - i)
                }
                t3 = 7 & (t1 | t2)
                if (uint64(rule) & pow2(uint(t3))) != 0 {
                    state |= pow2(i)
                }
            }
        }
        fmt.Printf("%d ", b)
    }
    fmt.Println()
}

func main() {
    evolve(1, 30)
}
Task: Statistics_Normal distribution




Go: package main

import (
    "fmt"
    "math"
    "math/rand"
    "strings"
)


func norm2() (s, c float64) {
    r := math.Sqrt(-2 * math.Log(rand.Float64()))
    s, c = math.Sincos(2 * math.Pi * rand.Float64())
    return s * r, c * r
}

func main() {
    const (
        n     = 10000
        bins  = 12
        sig   = 3
        scale = 100
    )
    var sum, sumSq float64
    h := make([]int, bins)
    for i, accum := 0, func(v float64) {
        sum += v
        sumSq += v * v
        b := int((v + sig) * bins / sig / 2)
        if b >= 0 && b < bins {
            h[b]++
        }
    }; i < n/2; i++ {
        v1, v2 := norm2()
        accum(v1)
        accum(v2)
    }
    m := sum / n
    fmt.Println("mean:", m)
    fmt.Println("stddev:", math.Sqrt(sumSq/float64(n)-m*m))
    for _, p := range h {
        fmt.Println(strings.Repeat("*", p/scale))
    }
}
Task: Vogel's approximation method




Go: #include <stdio.h>
#include <limits.h>
 
#define TRUE 1
#define FALSE 0
#define N_ROWS 5
#define N_COLS 5
 
typedef int bool;
 
int supply[N_ROWS] = { 461, 277, 356, 488,  393 };
int demand[N_COLS] = { 278,  60, 461, 116, 1060 };
 
int costs[N_ROWS][N_COLS] = {
    { 46,  74,  9, 28, 99 },
    { 12,  75,  6, 36, 48 },
    { 35, 199,  4,  5, 71 },
    { 61,  81, 44, 88,  9 },
    { 85,  60, 14, 25, 79 }
};


 
int main() {
    

    printf("     A    B    C    D    E\n");
    for (i = 0; i < N_ROWS; ++i) {
        printf("%c", 'V' + i);
        for (j = 0; j < N_COLS; ++j) printf("  %3d", results[i][j]);
        printf("\n");
    }
    printf("\nTotal cost = %d\n", total_cost);
    return 0;
}
Task: Minimum positive multiple in base 10 using only 0 and 1




Go: package main

import (
    "fmt"
    "github.com/shabbyrobe/go-num"
    "strings"
    "time"
)

func b10(n int64) {
    if n == 1 {
        fmt.Printf("%4d: %28s  %-24d\n", 1, "1", 1)
        return
    }
    n1 := n + 1
    pow := make([]int64, n1)
    val := make([]int64, n1)
    var count, ten, x int64 = 0, 1, 1
    for ; x < n1; x++ {
        val[x] = ten
        for j := int64(0); j < n1; j++ {
            if pow[j] != 0 && pow[(j+ten)%n] == 0 && pow[j] != x {
                pow[(j+ten)%n] = x
            }
        }
        if pow[ten] == 0 {
            pow[ten] = x
        }
        ten = (10 * ten) % n
        if pow[0] != 0 {
            break
        }
    }
    x = n
    if pow[0] != 0 {
        s := ""
        for x != 0 {
            p := pow[x%n]
            if count > p {
                s += strings.Repeat("0", int(count-p))
            }
            count = p - 1
            s += "1"
            x = (n + x - val[p]) % n
        }
        if count > 0 {
            s += strings.Repeat("0", int(count))
        }
        mpm := num.MustI128FromString(s)
        mul := mpm.Quo64(n)
        fmt.Printf("%4d: %28s  %-24d\n", n, s, mul)
    } else {
        fmt.Println("Can't do it!")
    }
}

func main() {
    start := time.Now()
    tests := [][]int64{{1, 10}, {95, 105}, {297}, {576}, {594}, {891}, {909}, {999},
        {1998}, {2079}, {2251}, {2277}, {2439}, {2997}, {4878}}
    fmt.Println("   n                           B10  multiplier")
    fmt.Println("----------------------------------------------")
    for _, test := range tests {
        from := test[0]
        to := from
        if len(test) == 2 {
            to = test[1]
        }
        for n := from; n <= to; n++ {
            b10(n)
        }
    }
    fmt.Printf("\nTook %s\n", time.Since(start))
}