WeixiangYan/CodeTransOcean huggingface dataset:
Task: Audio frequency generator




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    freq := 0
    for freq < 40 || freq > 10000 {
        fmt.Print("Enter frequency in Hz (40 to 10000) : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        freq, _ = strconv.Atoi(input)
    }
    freqS := strconv.Itoa(freq)

    vol := 0
    for vol < 1 || vol > 50 {
        fmt.Print("Enter volume in dB (1 to 50) : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        vol, _ = strconv.Atoi(input)
    }
    volS := strconv.Itoa(vol)

    dur := 0.0
    for dur < 2 || dur > 10 {
        fmt.Print("Enter duration in seconds (2 to 10) : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        dur, _ = strconv.ParseFloat(input, 64)
    }
    durS := strconv.FormatFloat(dur, 'f', -1, 64)

    kind := 0
    for kind < 1 || kind > 3 {
        fmt.Print("Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        kind, _ = strconv.Atoi(input)
    }
    kindS := "sine"
    if kind == 2 {
        kindS = "square"
    } else if kind == 3 {
        kindS = "sawtooth"
    }

    args := []string{"-n", "synth", durS, kindS, freqS, "vol", volS, "dB"}
    cmd := exec.Command("play", args...)
    err := cmd.Run()
    check(err)
}
Task: Rosetta Code_Rank languages by number of users




Go: package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "regexp"
    "sort"
    "strconv"
)

type Result struct {
    lang  string
    users int
}

func main() {
    const minimum = 25
    ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
    re := regexp.MustCompile(ex)
    page := "http:
    action := "action=query"
    format := "format=json"
    fversion := "formatversion=2"
    generator := "generator=categorymembers"
    gcmTitle := "gcmtitle=Category:Language%20users"
    gcmLimit := "gcmlimit=500"
    prop := "prop=categoryinfo"
    rawContinue := "rawcontinue="
    page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
        generator, gcmTitle, gcmLimit, prop, rawContinue)
    resp, _ := http.Get(page)
    body, _ := ioutil.ReadAll(resp.Body)
    matches := re.FindAllStringSubmatch(string(body), -1)
    resp.Body.Close()
    var results []Result
    for _, match := range matches {
        if len(match) == 5 {
            users, _ := strconv.Atoi(match[4]) 
            if users >= minimum {
                result := Result{match[1], users}
                results = append(results, result)
            }
        }
    }
    sort.Slice(results, func(i, j int) bool {
        return results[j].users < results[i].users
    })

    fmt.Println("Rank  Users  Language")
    fmt.Println("----  -----  --------")
    rank := 0
    lastUsers := 0
    lastRank := 0
    for i, result := range results {
        eq := " "
        rank = i + 1
        if lastUsers == result.users {
            eq = "="
            rank = lastRank
        } else {
            lastUsers = result.users
            lastRank = rank
        }
        fmt.Printf(" %-2d%s   %3d    %s\n", rank, eq, result.users, result.lang)
    }
}
Task: HTTPS_Client-authenticated




Go: package main

import (
	"crypto/tls"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {

	
	cert, err := tls.LoadX509KeyPair(
		"./client.local.tld/client.local.tld.crt",
		"./client.local.tld/client.local.tld.key",
	)

	if err != nil {
		log.Fatal("Error while loading x509 key pair", err)
	}

	
	tlsConfig := &tls.Config{Certificates: []tls.Certificate{cert}}

	tlsConfig.BuildNameToCertificate()
	transport := &http.Transport{TLSClientConfig: tlsConfig}

	
	client := &http.Client{Transport: transport}

	res, err := client.Get("https:
	if err != nil {
		log.Fatal(err)
	}
	contents, err := ioutil.ReadAll(res.Body)
	log.Print(string(contents))

}
Task: CalmoSoft primes




Go: package main

import (
    "fmt"
    "math/big"
    "rcu"
    "time"
)

var start = time.Now()

const max = 50_000_000

var primes = rcu.Primes(max)

func calmoPrimes(limit int) (int, []int, []int, []int) {
    var pc, sum int
    if limit < max {
        for i := 0; i < len(primes); i++ {
            if primes[i] > limit {
                pc = i
                break
            }
        }
    } else {
        pc = len(primes)
    }
    for i := 0; i < pc; i++ {
        sum += primes[i]
    }
    longest := 0
    var sIndices, eIndices, sums []int
    for i := 0; i < pc; i++ {
        if pc-i < longest {
            break
        }
        if i > 0 {
            sum -= primes[i-1]
        }
        isEven := i == 0
        sum2 := sum
        for j := pc - 1; j >= i; j-- {
            temp := j - i + 1
            if temp < longest {
                break
            }
            if j < pc-1 {
                sum2 -= primes[j+1]
            }
            if (temp % 2) == 0 != isEven {
                continue
            }
            bsum := big.NewInt(int64(sum2))
            if bsum.ProbablyPrime(5) {
                if temp > longest {
                    longest = temp
                    sIndices = []int{i}
                    eIndices = []int{j}
                    sums = []int{sum2}
                } else {
                    sIndices = append(sIndices, i)
                    eIndices = append(eIndices, j)
                    sums = append(sums, sum2)
                }
                break
            }
        }
    }
    return longest, sIndices, eIndices, sums
}

func main() {
    for _, limit := range []int{100, 250, 5000, 10000, 500000, 50000000} {
        longest, sIndices, eIndices, sums := calmoPrimes(limit)
        fmt.Println("For primes up to", rcu.Commatize(limit), "the longest sequence(s) of CalmoSoft primes")
        fmt.Println("having a length of", rcu.Commatize(longest), "is/are:\n")
        for i := 0; i < len(sIndices); i++ {
            cp1 := primes[sIndices[i] : sIndices[i]+6]
            cp2 := primes[eIndices[i]-5 : eIndices[i]+1]
            cps := ""
            for _, p := range cp1 {
                cps += fmt.Sprintf("%d + ", p)
            }
            cps += ".. + "
            for _, p := range cp2 {
                cps += fmt.Sprintf("%d + ", p)
            }
            fmt.Printf("%s = %s\n", cps[:len(cps)-3], rcu.Commatize(sums[i]))
        }
        fmt.Println()
    }
    fmt.Printf("Took %d ms\n", time.Since(start).Milliseconds())
}
Task: SQL-based authentication




Go: package main

import (
    "bytes"
    "crypto/md5"
    "crypto/rand"
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func connectDB() (*sql.DB, error) {
    return sql.Open("mysql", "rosetta:code@/rc")
}

func createUser(db *sql.DB, user, pwd string) error {
    salt := make([]byte, 16)
    rand.Reader.Read(salt)
    _, err := db.Exec(`insert into users (username, pass_salt, pass_md5)
        values (?, ?, ?)`, user, salt, saltHash(salt, pwd))
    if err != nil {
        return fmt.Errorf("User %s already exits", user)
    }
    return nil
}

func authenticateUser(db *sql.DB, user, pwd string) error {
    var salt, hash []byte
    row := db.QueryRow(`select pass_salt, pass_md5 from users
        where username=?`, user)
    if err := row.Scan(&salt, &hash); err != nil {
        return fmt.Errorf("User %s unknown", user)
    }
    if !bytes.Equal(saltHash(salt, pwd), hash) {
        return fmt.Errorf("User %s invalid password", user)
    }
    return nil
}

func saltHash(salt []byte, pwd string) []byte {
    h := md5.New()
    h.Write(salt)
    h.Write([]byte(pwd))
    return h.Sum(nil)
}

func main() {
    
    db, err := connectDB()
    defer db.Close()
    createUser(db, "sam", "123")
    err = authenticateUser(db, "sam", "123")
    if err == nil {
        fmt.Println("User sam authenticated")
    }

    
    fmt.Println()
    
    rows, _ := db.Query(`select username, pass_salt, pass_md5 from users`)
    var user string
    var salt, hash []byte
    for rows.Next() {
        rows.Scan(&user, &salt, &hash)
        fmt.Printf("%s %x %x\n", user, salt, hash)
    }
    
    err = createUser(db, "sam", "123")
    fmt.Println(err)
    
    err = authenticateUser(db, "pam", "123")
    fmt.Println(err)
    
    err = authenticateUser(db, "sam", "1234")
    fmt.Println(err)
    
    db.Exec(`truncate table users`)
}
Task: Bitmap_PPM conversion through a pipe




Go: package main





import (
    "fmt"
    "math/rand"
    "os/exec"
    "raster"
)

func main() {
    b := raster.NewBitmap(400, 300)
    
    b.FillRgb(0xc08040)
    for i := 0; i < 2000; i++ {
        b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
    }
    for x := 0; x < 400; x++ {
        for y := 240; y < 245; y++ {
            b.SetPxRgb(x, y, 0x804020)
        }
        for y := 260; y < 265; y++ {
            b.SetPxRgb(x, y, 0x804020)
        }
    }
    for y := 0; y < 300; y++ {
        for x := 80; x < 85; x++ {
            b.SetPxRgb(x, y, 0x804020)
        }
        for x := 95; x < 100; x++ {
            b.SetPxRgb(x, y, 0x804020)
        }
    }

    
    c := exec.Command("cjpeg", "-outfile", "pipeout.jpg")
    pipe, err := c.StdinPipe()
    if err != nil {
        fmt.Println(err)
        return
    }
    err = c.Start()
    if err != nil {
        fmt.Println(err)
        return
    }
    err = b.WritePpmTo(pipe)
    if err != nil {
        fmt.Println(err)
        return
    }
    err = pipe.Close()
    if err != nil {
        fmt.Println(err)
    }
}
Task: Singular value decomposition




Go: <package main

import (
    "fmt"
    "gonum.org/v1/gonum/mat"
    "log"
)

func matPrint(m mat.Matrix) {
    fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
    fmt.Printf("%13.10f\n", fa)
}

func main() {
    var svd mat.SVD
    a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})
    ok := svd.Factorize(a, mat.SVDFull)
    if !ok {
        log.Fatal("Something went wrong!")
    }
    u := mat.NewDense(2, 2, nil)
    svd.UTo(u)
    fmt.Println("U:")
    matPrint(u)
    values := svd.Values(nil)
    sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})
    fmt.Println("\nΣ:")
    matPrint(sigma)
    vt := mat.NewDense(2, 2, nil)
    svd.VTo(vt)
    fmt.Println("\nVT:")
    matPrint(vt)
}
Task: Tarjan




Go: package main

import (
    "fmt"
    "math/big"
)


var g = [][]int{
    0: {1},
    2: {0},
    5: {2, 6},
    6: {5},
    1: {2},
    3: {1, 2, 4},
    4: {5, 3},
    7: {4, 7, 6},
}

func main() {
    tarjan(g, func(c []int) { fmt.Println(c) })
}



func tarjan(g [][]int, emit func([]int)) {
    var indexed, stacked big.Int
    index := make([]int, len(g))
    lowlink := make([]int, len(g))
    x := 0
    var S []int
    var sc func(int) bool
    sc = func(n int) bool {
        index[n] = x
        indexed.SetBit(&indexed, n, 1)
        lowlink[n] = x
        x++
        S = append(S, n)
        stacked.SetBit(&stacked, n, 1)
        for _, nb := range g[n] {
            if indexed.Bit(nb) == 0 {
                if !sc(nb) {
                    return false
                }
                if lowlink[nb] < lowlink[n] {
                    lowlink[n] = lowlink[nb]
                }
            } else if stacked.Bit(nb) == 1 {
                if index[nb] < lowlink[n] {
                    lowlink[n] = index[nb]
                }
            }
        }
        if lowlink[n] == index[n] {
            var c []int
            for {
                last := len(S) - 1
                w := S[last]
                S = S[:last]
                stacked.SetBit(&stacked, w, 0)
                c = append(c, w)
                if w == n {
                    emit(c)
                    break
                }
            }
        }
        return true
    }
    for n := range g {
        if indexed.Bit(n) == 0 && !sc(n) {
            return
        }
    }
}
Task: Compiler_Verifying syntax




Go: package main

import (
    "fmt"
    "go/parser"
    "regexp"
    "strings"
)

var (
    re1 = regexp.MustCompile(`[^_a-zA-Z0-9\+\-\*/=<\(\)\s]`)
    re2 = regexp.MustCompile(`\b_\w*\b`)
    re3 = regexp.MustCompile(`[=<+*/-]\s*not`)
    re4 = regexp.MustCompile(`(=|<)\s*[^(=< ]+\s*([=<+*/-])`)
)

var subs = [][2]string{
    {"=", "=="}, {" not ", " ! "}, {"(not ", "(! "}, {" or ", " || "}, {" and ", " && "},
}

func possiblyValid(expr string) error {
    matches := re1.FindStringSubmatch(expr)
    if matches != nil {
        return fmt.Errorf("invalid character %q found", []rune(matches[0])[0])
    }
    if re2.MatchString(expr) {
        return fmt.Errorf("identifier cannot begin with an underscore")
    }
    if re3.MatchString(expr) {
        return fmt.Errorf("expected operand, found 'not'")
    }
    matches = re4.FindStringSubmatch(expr)
    if matches != nil {
        return fmt.Errorf("operator %q is non-associative", []rune(matches[1])[0])
    }
    return nil
}

func modify(err error) string {
    e := err.Error()
    for _, sub := range subs {
        e = strings.ReplaceAll(e, strings.TrimSpace(sub[1]), strings.TrimSpace(sub[0]))
    }
    return strings.Split(e, ":")[2][1:] 
}

func main() {
    exprs := []string{
        "$",
        "one",
        "either or both",
        "a + 1",
        "a + b < c",
        "a = b",
        "a or b = c",
        "3 + not 5",
        "3 + (not 5)",
        "(42 + 3",
        "(42 + 3)",
        " not 3 < 4 or (true or 3 /  4 + 8 *  5 - 5 * 2 < 56) and 4 * 3  < 12 or not true",
        " and 3 < 2",
        "not 7 < 2",
        "2 < 3 < 4",
        "2 < (3 < 4)",
        "2 < foobar - 3 < 4",
        "2 < foobar and 3 < 4",
        "4 * (32 - 16) + 9 = 73",
        "235 76 + 1",
        "true or false = not true",
        "true or false = (not true)",
        "not true or false = false",
        "not true = false",
        "a + b = not c and false",
        "a + b = (not c) and false",
        "a + b = (not c and false)",
        "ab_c / bd2 or < e_f7",
        "g not = h",
        "été = false",
        "i++",
        "j & k",
        "l or _m",
    } 
   
    for _, expr := range exprs {
        fmt.Printf("Statement to verify: %q\n", expr)
        if err := possiblyValid(expr); err != nil {
            fmt.Printf("\"false\" -> %s\n\n", err.Error())
            continue
        }
        expr = fmt.Sprintf(" %s ", expr) 
        for _, sub := range subs {
            expr = strings.ReplaceAll(expr, sub[0], sub[1])
        }
        _, err := parser.ParseExpr(expr)
        if err != nil {
            fmt.Println(`"false" ->`, modify(err))
        } else {
            fmt.Println(`"true"`)
        }
        fmt.Println()
    }
}
Task: Rosetta Code_List authors of task descriptions




Go: package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "regexp"
    "sort"
    "strings"
)

type authorNumber struct {
    author string
    number int
}

func main() {
    ex1 := `<li><a href="/wiki/(.*?)"`
    ex2 := `a href="/(wiki/User:|mw/index\.php\?title=User:|wiki/Special:Contributions/)([^"&]+)`
    re1 := regexp.MustCompile(ex1)
    re2 := regexp.MustCompile(ex2)
    url1 := "http:
    url2 := "http:
    urls := []string{url1, url2}
    var tasks []string
    for _, url := range urls {
        resp, _ := http.Get(url)
        body, _ := ioutil.ReadAll(resp.Body)
        
        matches := re1.FindAllStringSubmatch(string(body), -1)
        resp.Body.Close()
        for _, match := range matches {
            
            if !strings.HasPrefix(match[1], "Category:") {
                tasks = append(tasks, match[1])
            }
        }
    }
    authors := make(map[string]int)
    for _, task := range tasks {
        
        page := fmt.Sprintf("http:
        resp, _ := http.Get(page)
        body, _ := ioutil.ReadAll(resp.Body)
        
        matches := re2.FindAllStringSubmatch(string(body), -1)
        resp.Body.Close()
        
        author := matches[len(matches)-1][2]
        author = strings.ReplaceAll(author, "_", " ")
        
        authors[author]++
    }
    
    authorNumbers := make([]authorNumber, 0, len(authors))
    for k, v := range authors {
        authorNumbers = append(authorNumbers, authorNumber{k, v})
    }
    sort.Slice(authorNumbers, func(i, j int) bool {
        return authorNumbers[i].number > authorNumbers[j].number
    })
    
    fmt.Println("Total tasks   :", len(tasks))
    fmt.Println("Total authors :", len(authors))
    fmt.Println("\nThe top 20 authors by number of tasks created are:\n")
    fmt.Println("Pos  Tasks  Author")
    fmt.Println("===  =====  ======")
    lastNumber, lastIndex := 0, -1
    for i, authorNumber := range authorNumbers[0:20] {
        j := i
        if authorNumber.number == lastNumber {
            j = lastIndex
        } else {
            lastIndex = i
            lastNumber = authorNumber.number
        }
        fmt.Printf("%2d:   %3d   %s\n", j+1, authorNumber.number, authorNumber.author)
    }
}
Task: Waveform analysis_Top and tail




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    const sec = "00:00:01"
    scanner := bufio.NewScanner(os.Stdin)
    name := ""
    for name == "" {
        fmt.Print("Enter name of audio file to be trimmed : ")
        scanner.Scan()
        name = scanner.Text()
        check(scanner.Err())
    }

    name2 := ""
    for name2 == "" {
        fmt.Print("Enter name of output file              : ")
        scanner.Scan()
        name2 = scanner.Text()
        check(scanner.Err())
    }    
    
    squelch := 0.0
    for squelch < 1 || squelch > 10 {
        fmt.Print("Enter squelch level % max (1 to 10)    : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        squelch, _ = strconv.ParseFloat(input, 64)
    }
    squelchS := strconv.FormatFloat(squelch, 'f', -1, 64) + "%"

    tmp1 := "tmp1_" + name
    tmp2 := "tmp2_" + name

    
    args := []string{name, tmp1, "silence", "1", sec, squelchS}
    cmd := exec.Command("sox", args...)
    err := cmd.Run()
    check(err) 

    
    args = []string{tmp1, tmp2, "reverse"}     
    cmd = exec.Command("sox", args...)
    err = cmd.Run()
    check(err)

    
    args = []string{tmp2, tmp1, "silence", "1", sec, squelchS}
    cmd  = exec.Command("sox", args...)
    err = cmd.Run()
    check(err)

    
    args = []string{tmp1, name2, "reverse"}    
    cmd = exec.Command("sox", args...)
    err = cmd.Run()
    check(err)

    
    err = os.Remove(tmp1)
    check(err)
    err = os.Remove(tmp2)
    check(err)
}
Task: Numbers which are not the sum of distinct squares




Go: package main

import (
    "fmt"
    "math"
    "rcu"
)

func contains(a []int, n int) bool {
    for _, e := range a {
        if e == n {
            return true
        }
    }
    return false
}


func soms(n int, f []int) bool {
    if n <= 0 {
        return false
    }
    if contains(f, n) {
        return true
    }
    sum := rcu.SumInts(f)
    if n > sum {
        return false
    }
    if n == sum {
        return true
    }
    rf := make([]int, len(f))
    copy(rf, f)
    for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 {
        rf[i], rf[j] = rf[j], rf[i]
    }
    rf = rf[1:]
    return soms(n-f[len(f)-1], rf) || soms(n, rf)
}

func main() {
    var s, a []int
    sf := "\nStopped checking after finding %d sequential non-gaps after the final gap of %d\n"
    i, g := 1, 1
    for g >= (i >> 1) {
        r := int(math.Sqrt(float64(i)))
        if r*r == i {
            s = append(s, i)
        }
        if !soms(i, s) {
            g = i
            a = append(a, g)
        }
        i++
    }
    fmt.Println("Numbers which are not the sum of distinct squares:")
    fmt.Println(a)
    fmt.Printf(sf, i-g, g)
    fmt.Printf("Found %d in total\n", len(a))
}

var r int
Task: Time-based one-time password algorithm




Go: 


package onetime

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/binary"
	"errors"
	"hash"
	"math"
	"time"
)


type OneTimePassword struct {
	Digit    int              
	TimeStep time.Duration    
	BaseTime time.Time        
	Hash     func() hash.Hash 
}


func (otp *OneTimePassword) HOTP(secret []byte, count uint64) uint {
	hs := otp.hmacSum(secret, count)
	return otp.truncate(hs)
}

func (otp *OneTimePassword) hmacSum(secret []byte, count uint64) []byte {
	mac := hmac.New(otp.Hash, secret)
	binary.Write(mac, binary.BigEndian, count)
	return mac.Sum(nil)
}

func (otp *OneTimePassword) truncate(hs []byte) uint {
	sbits := dt(hs)
	snum := uint(sbits[3]) | uint(sbits[2])<<8
	snum |= uint(sbits[1])<<16 | uint(sbits[0])<<24
	return snum % uint(math.Pow(10, float64(otp.Digit)))
}




func Simple(digit int) (otp OneTimePassword, err error) {
	if digit < 6 {
		err = errors.New("minimum of 6 digits is required for a valid HTOP code")
		return
	} else if digit > 9 {
		err = errors.New("HTOP code cannot be longer than 9 digits")
		return
	}
	const step = 30 * time.Second
	otp = OneTimePassword{digit, step, time.Unix(0, 0), sha1.New}
	return
}


func (otp *OneTimePassword) TOTP(secret []byte) uint {
	return otp.HOTP(secret, otp.steps(time.Now()))
}

func (otp *OneTimePassword) steps(now time.Time) uint64 {
	elapsed := now.Unix() - otp.BaseTime.Unix()
	return uint64(float64(elapsed) / otp.TimeStep.Seconds())
}

func dt(hs []byte) []byte {
	offset := int(hs[len(hs)-1] & 0xf)
	p := hs[offset : offset+4]
	p[0] &= 0x7f
	return p
}
Task: Powerful numbers




Go: package main

import (
    "fmt"
    "math"
    "sort"
)

const adj = 0.0001 

var primes = []uint64{
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
} 

func gcd(x, y uint64) uint64 {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

func isSquareFree(x uint64) bool {
    for _, p := range primes {
        p2 := p * p
        if p2 > x {
            break
        }
        if x%p2 == 0 {
            return false
        }
    }
    return true
}

func iroot(x, p uint64) uint64 {
    return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}

func ipow(x, p uint64) uint64 {
    prod := uint64(1)
    for p > 0 {
        if p&1 != 0 {
            prod *= x
        }
        p >>= 1
        x *= x
    }
    return prod
}

func powerful(n, k uint64) []uint64 {
    set := make(map[uint64]bool)
    var f func(m, r uint64) 
    f = func(m, r uint64) {
        if r < k {
            set[m] = true
            return
        }
        for v := uint64(1); v <= iroot(n/m, r); v++ {
            if r > k {
                if !isSquareFree(v) || gcd(m, v) != 1 {
                    continue
                }
            }
            f(m*ipow(v, r), r-1)
        }
    }
    f(1, (1<<k)-1)
    list := make([]uint64, 0, len(set))
    for key := range set {
        list = append(list, key)
    }
    sort.Slice(list, func(i, j int) bool {
        return list[i] < list[j]
    })
    return list
}

func main() {
    power := uint64(10)
    for k := uint64(2); k <= 10; k++ {
        power *= 10
        a := powerful(power, k)
        le := len(a)
        h, t := a[0:5], a[le-5:]
        fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
    }
    fmt.Println()
    for k := uint64(2); k <= 10; k++ {
        power := uint64(1)
        var counts []int
        for j := uint64(0); j < k+10; j++ {
            a := powerful(power, k)
            counts = append(counts, len(a))
            power *= 10
        }
        j := k + 10
        fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
    }
}