WeixiangYan/CodeTransOcean huggingface dataset:
Task: Smallest numbers




Go: package main

import (
    "fmt"
    "math/big"
    "strconv"
    "strings"
)

func main() {
    var res []int64
    for n := 0; n <= 50; n++ {
        ns := strconv.Itoa(n)
        k := int64(1)
        for {
            bk := big.NewInt(k)
            s := bk.Exp(bk, bk, nil).String()
            if strings.Contains(s, ns) {
                res = append(res, k)
                break
            }
            k++
        }
    }
    fmt.Println("The smallest positive integers K where K ^ K contains N (0..50) are:")
    for i, n := range res {
        fmt.Printf("%2d ", n)
        if (i+1)%17 == 0 {
            fmt.Println()
        }
    }
}




Python: 

import sys

if len(sys.argv)!=2:
    print("Usage : python " + sys.argv[0] + " <whole number>")
    exit()

numLimit = int(sys.argv[1])

resultSet = {}

base = 1

while len(resultSet)!=numLimit:
    result = base**base

    for i in range(0,numLimit):
        if str(i) in str(result) and i not in resultSet:
            resultSet[i] = base

    base+=1

[print(resultSet[i], end=' ') for i in sorted(resultSet)]
Task: Safe and Sophie Germain primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var sgp []int
    p := 2
    count := 0
    for count < 50 {
        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {
            sgp = append(sgp, p)
            count++
        }
        if p != 2 {
            p = p + 2
        } else {
            p = 3
        }
    }
    fmt.Println("The first 50 Sophie Germain primes are:")
    for i := 0; i < len(sgp); i++ {
        fmt.Printf("%5s ", rcu.Commatize(sgp[i]))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
}




Python: print("working...")
row = 0
limit = 1500
Sophie = []

def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

for n in range(2,limit):
	p = 2*n + 1
	if isPrime(n) and isPrime(p):
		Sophie.append(n)

print("Found ",end = "")
print(len(Sophie),end = "")
print(" Safe and Sophie primes.")

print(Sophie)
print("done...")
Task: Sort primes from list to a list




Go: package main

import (
    "fmt"
    "rcu"
    "sort"
)

func main() {
    list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}
    var primes []int
    for _, e := range list {
        if rcu.IsPrime(e) {
            primes = append(primes, e)
        }
    }
    sort.Ints(primes)
    fmt.Println(primes)
}




Python: print("working...")
print("Primes are:")

def isprime(m):
    for i in range(2,int(m**0.5)+1):
        if m%i==0:
            return False
    return True

Primes = [2,43,81,122,63,13,7,95,103]
Temp = []

for n in range(len(Primes)):
	if isprime(Primes[n]):
		Temp.append(Primes[n])

Temp.sort()
print(Temp)
print("done...")
Task: Count the coins_0-1




Go: package main

import "fmt"

var cnt = 0  
var cnt2 = 0 
var wdth = 0 

func factorial(n int) int {
    prod := 1
    for i := 2; i <= n; i++ {
        prod *= i
    }
    return prod
}

func count(want int, used []int, sum int, have, uindices, rindices []int) {
    if sum == want {
        cnt++
        cnt2 += factorial(len(used))
        if cnt < 11 {
            uindicesStr := fmt.Sprintf("%v", uindices)
            fmt.Printf("  indices %*s => used %v\n", wdth, uindicesStr, used)
        }
    } else if sum < want && len(have) != 0 {
        thisCoin := have[0]
        index := rindices[0]
        rest := have[1:]
        rindices := rindices[1:]
        count(want, append(used, thisCoin), sum+thisCoin, rest,
            append(uindices, index), rindices)
        count(want, used, sum, rest, uindices, rindices)
    }
}

func countCoins(want int, coins []int, width int) {
    fmt.Printf("Sum %d from coins %v\n", want, coins)
    cnt = 0
    cnt2 = 0
    wdth = -width
    rindices := make([]int, len(coins))
    for i := range rindices {
        rindices[i] = i
    }
    count(want, []int{}, 0, coins, []int{}, rindices)
    if cnt > 10 {
        fmt.Println("  .......")
        fmt.Println("  (only the first 10 ways generated are shown)")
    }
    fmt.Println("Number of ways - order unimportant :", cnt, "(as above)")
    fmt.Println("Number of ways - order important   :", cnt2, "(all perms of above indices)\n")
}

func main() {
    countCoins(6, []int{1, 2, 3, 4, 5}, 7)
    countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9)
    countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20)
}




Python: from itertools import product, compress

fact = lambda n: n and n*fact(n - 1) or 1
combo_count = lambda total, coins, perm:\
                    sum(perm and fact(len(x)) or 1
                        for x in (list(compress(coins, c))
                                  for c in product(*([(0, 1)]*len(coins))))
                        if sum(x) == total)

cases = [(6,  [1, 2, 3, 4, 5]),
         (6,  [1, 1, 2, 3, 3, 4, 5]),
         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]

for perm in [False, True]:
    print(f'Order matters: {perm}')
    for s, c in cases:
        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')
    print()
Task: Find first missing positive




Go: package main

import (
    "fmt"
    "sort"
)

func firstMissingPositive(a []int) int {
    var b []int
    for _, e := range a {
        if e > 0 {
            b = append(b, e)
        }
    }
    sort.Ints(b)
    le := len(b)
    if le == 0 || b[0] > 1 {
        return 1
    }
    for i := 1; i < le; i++ {
        if b[i]-b[i-1] > 1 {
            return b[i-1] + 1
        }
    }
    return b[le-1] + 1
}

func main() {
    fmt.Println("The first missing positive integers for the following arrays are:\n")
    aa := [][]int{
        {1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}, {1, 2, 3, 4, 5},
        {-6, -5, -2, -1}, {5, -5}, {-2}, {1}, {}}
    for _, a := range aa {
        fmt.Println(a, "->", firstMissingPositive(a))
    }
}




Python: 

from itertools import count



def firstGap(xs):
    
    return next(x for x in count(1) if x not in xs)




def main():
    
    print('\n'.join([
        f'{repr(xs)} -> {firstGap(xs)}' for xs in [
            [1, 2, 0],
            [3, 4, -1, 1],
            [7, 8, 9, 11, 12]
        ]
    ]))



if __name__ == '__main__':
    main()
Task: Magic constant




Go: package main

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

func magicConstant(n int) int {
    return (n*n + 1) * n / 2
}

var ss = []string{
    "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074",
    "\u2075", "\u2076", "\u2077", "\u2078", "\u2079",
}

func superscript(n int) string {
    if n < 10 {
        return ss[n]
    }
    if n < 20 {
        return ss[1] + ss[n-10]
    }
    return ss[2] + ss[0]
}

func main() {
    fmt.Println("First 20 magic constants:")
    for n := 3; n <= 22; n++ {
        fmt.Printf("%5d ", magicConstant(n))
        if (n-2)%10 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\n1,000th magic constant:", rcu.Commatize(magicConstant(1002)))

    fmt.Println("\nSmallest order magic square with a constant greater than:")
    for i := 1; i <= 20; i++ {
        goal := math.Pow(10, float64(i))
        order := int(math.Cbrt(goal*2)) + 1
        fmt.Printf("10%-2s : %9s\n", superscript(i), rcu.Commatize(order))
    }
}




Python: 

def a(n):
    n += 2
    return n*(n**2 + 1)/2
 
def inv_a(x):
    k = 0
    while k*(k**2+1)/2+2 < x:
        k+=1
    return k

 
if __name__ == '__main__':
    print("The first 20 magic constants are:");
    for n in range(1, 20):
        print(int(a(n)), end = " ");
    print("\nThe 1,000th magic constant is:",int(a(1000)));
     
    for e in range(1, 20):
        print(f'10^{e}: {inv_a(10**e)}');
Task: Find minimum number of coins that make a given value




Go: package main

import "fmt"

func main() {
    denoms := []int{200, 100, 50, 20, 10, 5, 2, 1}
    coins := 0
    amount := 988
    remaining := 988
    fmt.Println("The minimum number of coins needed to make a value of", amount, "is as follows:")
    for _, denom := range denoms {
        n := remaining / denom
        if n > 0 {
            coins += n
            fmt.Printf("  %3d x %d\n", denom, n)
            remaining %= denom
            if remaining == 0 {
                break
            }
        }
    }
    fmt.Println("\nA total of", coins, "coins in all.")
}




Python: def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988):
    print(f"Available denominations: {denominations}. Total is to be: {total}.")
    coins, remaining = sorted(denominations, reverse=True), total
    for n in range(len(coins)):
        coinsused, remaining = divmod(remaining, coins[n])
        if coinsused > 0:
            print("   ", coinsused, "*", coins[n])

makechange()
Task: Prime numbers which contain 123




Go: package main

import (
    "fmt"
    "rcu"
    "strings"
)

func main() {
    limit := 100_000
    primes := rcu.Primes(limit * 10)
    var results []int
    for _, p := range primes {
        if p < 1000 || p > 99999 {
            continue
        }
        ps := fmt.Sprintf("%s", p)
        if strings.Contains(ps, "123") {
            results = append(results, p)
        }
    }
    climit := rcu.Commatize(limit)
    fmt.Printf("Primes under %s which contain '123' when expressed in decimal:\n", climit)
    for i, p := range results {
        fmt.Printf("%7s ", rcu.Commatize(p))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n\nFound", len(results), "such primes under", climit, "\b.")

    limit = 1_000_000
    climit = rcu.Commatize(limit)
    count := len(results)
    for _, p := range primes {
        if p < 100_000 {
            continue
        }
        ps := fmt.Sprintf("%s", p)
        if strings.Contains(ps, "123") {
            count++
        }
    }
    fmt.Println("\nFound", count, "such primes under", climit, "\b.")
}




Python: 

def prime(limite, mostrar):
    global columna
    columna = 0
    
    for n in range(limite):
        strn = str(n)
        if isPrime(n) and ('123' in str(n)):
            columna += 1                
            if mostrar == True:
                print(n, end="  ");
                if columna % 8 == 0:
                    print('')
    return columna


if __name__ == "__main__":
    print("Números primos que contienen 123:")
    limite = 100000
    prime(limite, True)
    print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
    limite = 1000000
    prime(limite, False)
    print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
Task: Function frequency




Go: package main

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
    "io/ioutil"
    "os"
    "sort"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Println("usage ff <go source filename>")
        return
    }
    src, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println(err)
        return
    }
    fs := token.NewFileSet()
    a, err := parser.ParseFile(fs, os.Args[1], src, 0)
    if err != nil {
        fmt.Println(err)
        return
    }
    f := fs.File(a.Pos())
    m := make(map[string]int)
    ast.Inspect(a, func(n ast.Node) bool {
        if ce, ok := n.(*ast.CallExpr); ok {
            start := f.Offset(ce.Pos())
            end := f.Offset(ce.Lparen)
            m[string(src[start:end])]++
        }
        return true
    })
    cs := make(calls, 0, len(m))
    for k, v := range m {
        cs = append(cs, &call{k, v})
    }
    sort.Sort(cs)
    for i, c := range cs {
        fmt.Printf("%-20s %4d\n", c.expr, c.count)
        if i == 9 {
            break
        }
    }
}

type call struct {
    expr  string
    count int
}
type calls []*call

func (c calls) Len() int           { return len(c) }
func (c calls) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }




Python: import ast

class CallCountingVisitor(ast.NodeVisitor):

    def __init__(self):
        self.calls = {}

    def visit_Call(self, node):
        if isinstance(node.func, ast.Name):
            fun_name = node.func.id
            call_count = self.calls.get(fun_name, 0)
            self.calls[fun_name] = call_count + 1
        self.generic_visit(node)

filename = input('Enter a filename to parse: ')
with open(filename, encoding='utf-8') as f:
    contents = f.read()
root = ast.parse(contents, filename=filename) 
visitor = CallCountingVisitor()
visitor.visit(root)
top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10]
for name, count in top10:
    print(name,'called',count,'times')
Task: Cullen and Woodall numbers




Go: package main

import (
    "fmt"
    big "github.com/ncw/gmp"
)

func cullen(n uint) *big.Int {
    one := big.NewInt(1)
    bn := big.NewInt(int64(n))
    res := new(big.Int).Lsh(one, n)
    res.Mul(res, bn)
    return res.Add(res, one)
}

func woodall(n uint) *big.Int {
    res := cullen(n)
    return res.Sub(res, big.NewInt(2))
}

func main() {
    fmt.Println("First 20 Cullen numbers (n * 2^n + 1):")
    for n := uint(1); n <= 20; n++ {
        fmt.Printf("%d ", cullen(n))
    }

    fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):")
    for n := uint(1); n <= 20; n++ {
        fmt.Printf("%d ", woodall(n))
    }

    fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):")
    count := 0
    for n := uint(1); count < 5; n++ {
        cn := cullen(n)
        if cn.ProbablyPrime(15) {
            fmt.Printf("%d ", n)
            count++
        }
    }

    fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):")
    count = 0
    for n := uint(1); count < 12; n++ {
        cn := woodall(n)
        if cn.ProbablyPrime(15) {
            fmt.Printf("%d ", n)
            count++
        }
    }
    fmt.Println()
}




Python: print("working...")
print("First 20 Cullen numbers:")

for n in range(1,21):
    num = n*pow(2,n)+1
    print(str(num),end= " ")

print()
print("First 20 Woodall numbers:")

for n in range(1,21):
    num = n*pow(2,n)-1
    print(str(num),end=" ")

print()
print("done...")
Task: Prime triplets




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    c := rcu.PrimeSieve(5505, false)
    var triples [][3]int
    fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:")
    for i := 3; i < 5500; i += 2 {
        if !c[i] && !c[i+2] && !c[i+6] {
            triples = append(triples, [3]int{i, i + 2, i + 6})
        }
    }
    for _, triple := range triples {
        var t [3]string
        for i := 0; i < 3; i++ {
            t[i] = rcu.Commatize(triple[i])
        }
        fmt.Printf("%5s  %5s  %5s\n", t[0], t[1], t[2])
    }
    fmt.Println("\nFound", len(triples), "such prime triplets.")
}




Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

if __name__ == '__main__':
    for p in range(3, 5499, 2):
        if not isPrime(p+6):
            continue
        if not isPrime(p+2):
            continue
        if not isPrime(p):
            continue
        print(f'[{p} {p+2} {p+6}]')
Task: Conjugate a Latin verb




Go: package main

import (
    "fmt"
    "log"
)

var endings = [][]string{
    {"o", "as", "at", "amus", "atis", "ant"},
    {"eo", "es", "et", "emus", "etis", "ent"},
    {"o", "is", "it", "imus", "itis", "unt"},
    {"io", "is", "it", "imus", "itis", "iunt"},
}

var infinEndings = []string{"are", "ēre", "ere", "ire"}

var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"}

var englishEndings = []string{"", "", "s", "", "", ""}

func conjugate(infinitive, english string) {
    letters := []rune(infinitive)
    le := len(letters)
    if le < 4 {
        log.Fatal("Infinitive is too short for a regular verb.")
    }
    infinEnding := string(letters[le-3:])
    conj := -1
    for i, s := range infinEndings {
        if s == infinEnding {
            conj = i
            break
        }
    }
    if conj == -1 {
        log.Fatalf("Infinitive ending -%s not recognized.", infinEnding)
    }
    stem := string(letters[:le-3])
    fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english)
    for i, ending := range endings[conj] {
        fmt.Printf("    %s%-4s  %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i])
    }
    fmt.Println()
}

func main() {
    pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}}
    for _, pair := range pairs {
        conjugate(pair[0], pair[1])
    }
}




Python: 

 
def conjugate(infinitive): 
    if not infinitive[-3:] == "are":
        print("'", infinitive, "' non prima coniugatio verbi.\n", sep='')
        return False
    
    stem = infinitive[0:-3]
    if len(stem) == 0:
        print("\'", infinitive, "\' non satis diu conjugatus\n", sep='')
        return False

    print("Praesens indicativi temporis of '", infinitive, "':", sep='') 
    for ending in ("o", "as", "at", "amus", "atis", "ant"):
        print("     ", stem, ending, sep='')
    print()
 
 
if __name__ == '__main__':
    for infinitive in ("amare", "dare", "qwerty", "are"):
        conjugate(infinitive)
Task: Fortunate numbers




Go: package main

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

func main() {
    primes := rcu.Primes(379)
    primorial := big.NewInt(1)
    var fortunates []int
    bPrime := new(big.Int)
    for _, prime := range primes {
        bPrime.SetUint64(uint64(prime))
        primorial.Mul(primorial, bPrime)
        for j := 3; ; j += 2 {
            jj := big.NewInt(int64(j))
            bPrime.Add(primorial, jj)
            if bPrime.ProbablyPrime(5) {
                fortunates = append(fortunates, j)
                break
            }
        }
    }
    m := make(map[int]bool)
    for _, f := range fortunates {
        m[f] = true
    }
    fortunates = fortunates[:0]
    for k := range m {
        fortunates = append(fortunates, k)
    }
    sort.Ints(fortunates)
    fmt.Println("After sorting, the first 50 distinct fortunate numbers are:")
    for i, f := range fortunates[0:50] {
        fmt.Printf("%3d ", f)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
}




Python: from sympy.ntheory.generate import primorial
from sympy.ntheory import isprime

def fortunate_number(n):
    
    
    
    i = 3
    primorial_ = primorial(n)
    while True:
        if isprime(primorial_ + i):
            return i
        i += 2

fortunate_numbers = set()
for i in range(1, 76):
    fortunate_numbers.add(fortunate_number(i))


first50 = sorted(list(fortunate_numbers))[:50]

print('The first 50 fortunate numbers:')
print(('{:<3} ' * 10).format(*(first50[:10])))
print(('{:<3} ' * 10).format(*(first50[10:20])))
print(('{:<3} ' * 10).format(*(first50[20:30])))
print(('{:<3} ' * 10).format(*(first50[30:40])))
print(('{:<3} ' * 10).format(*(first50[40:])))
Task: Smallest multiple




Go: package main

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

func lcm(n int) *big.Int {
    lcm := big.NewInt(1)
    t := new(big.Int)
    for _, p := range rcu.Primes(n) {
        f := p
        for f*p <= n {
            f *= p
        }
        lcm.Mul(lcm, t.SetUint64(uint64(f)))
    }
    return lcm
}

func main() {
    fmt.Println("The LCMs of the numbers 1 to N inclusive is:")
    for _, i := range []int{10, 20, 200, 2000} {
        fmt.Printf("%4d: %s\n", i, lcm(i))
    }
}




Python: 

from math import gcd
from functools import reduce


def lcm(a, b):
    
    return 0 if 0 == a or 0 == b else (
        abs(a * b) // gcd(a, b)
    )


for i in [10, 20, 200, 2000]:
    print(str(i) + ':', reduce(lcm, range(1, i + 1)))
Task: Meissel–Mertens constant




Go: package main

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

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

func main() {
    const euler = 0.57721566490153286
    primes := rcu.Primes(1 << 31)
    pc := len(primes)
    sum := 0.0
    fmt.Println("Primes added         M")
    fmt.Println("------------  --------------")
    for i, p := range primes {
        rp := 1.0 / float64(p)
        sum += math.Log(1.0-rp) + rp
        c := i + 1
        if (c%1e7) == 0 || c == pc {
            fmt.Printf("%11s   %0.12f\n", rcu.Commatize(c), sum+euler)
        }
    }
}




Python: 

from math import log

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    Euler = 0.57721566490153286
    m = 0
    for x in range(2, 10_000_000):
        if isPrime(x):
            m += log(1-(1/x)) + (1/x)

    print("MM =", Euler + m)
Task: Unicode strings




Go:     var i int
    var u rune
    for i, u = range "voilà" {
        fmt.Println(i, u)
    }




Python: 


u = 'abcdé'
print(ord(u[-1]))
Task: Quadrat special primes




Go: package main

import (
    "fmt"
    "math"
)

func sieve(limit int) []bool {
    limit++
    
    c := make([]bool, limit) 
    c[0] = true
    c[1] = true
    
    p := 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 isSquare(n int) bool {
    s := int(math.Sqrt(float64(n)))
    return s*s == n
}

func commas(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    c := sieve(15999)
    fmt.Println("Quadrat special primes under 16,000:")
    fmt.Println(" Prime1  Prime2    Gap  Sqrt")
    lastQuadSpecial := 3
    gap := 1
    count := 1
    fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1)
    for i := 5; i < 16000; i += 2 {
        if c[i] {
            continue
        }
        gap = i - lastQuadSpecial
        if isSquare(gap) {
            sqrt := int(math.Sqrt(float64(gap)))
            fmt.Printf("%7s %7s %6s %4d\n", commas(lastQuadSpecial), commas(i), commas(gap), sqrt)
            lastQuadSpecial = i
            count++
        }
    }
    fmt.Println("\n", count+1, "such primes found.")
}




Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    p = 2
    j = 1
    print(2, end = " ");
    while True:
        while True:
            if isPrime(p + j*j):
                break
            j += 1
        p += j*j
        if p > 16000:
            break
        print(p, end = " ");
        j = 1
Task: Topic variable




Go: package main

import (
    "math"
    "os"
    "strconv"
    "text/template"
)

func sqr(x string) string {
    f, err := strconv.ParseFloat(x, 64)
    if err != nil {
        return "NA"
    }
    return strconv.FormatFloat(f*f, 'f', -1, 64)
}

func sqrt(x string) string {
    f, err := strconv.ParseFloat(x, 64)
    if err != nil {
        return "NA"
    }
    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)
}

func main() {
    f := template.FuncMap{"sqr": sqr, "sqrt": sqrt}
    t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}}
square: {{sqr .}}
square root: {{sqrt .}}
`))
    t.Execute(os.Stdout, "3")
}




Python: >>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>>