WeixiangYan/CodeTransOcean huggingface dataset:
Task: Classes


C++: PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive

OPTION PARSE FALSE


'---The class does the declaring for you

CLASS Books 
	public: 
		const char* title;
		const char* author; 
		const char* subject; 
		int book_id; 
END CLASS


'---pointer to an object declaration (we use a class called Books) 
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1  =  Books()


'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567


PRINT "Book title   : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author  : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"



Go: package main

import "fmt"




type picnicBasket struct {
    nServings int 
    corkscrew bool
}


func (b *picnicBasket) happy() bool {
    return b.nServings > 1 && b.corkscrew
}









func newPicnicBasket(nPeople int) *picnicBasket {
    
    
    
    
    return &picnicBasket{nPeople, nPeople > 0}
}


func main() {
    var pb picnicBasket          
    pbl := picnicBasket{}        
    pbp := &picnicBasket{}       
    pbn := new(picnicBasket)     
    forTwo := newPicnicBasket(2) 
    
    forToo := &picnicBasket{nServings: 2, corkscrew: true}

    fmt.Println(pb.nServings, pb.corkscrew)
    fmt.Println(pbl.nServings, pbl.corkscrew)
    fmt.Println(pbp)
    fmt.Println(pbn)
    fmt.Println(forTwo)
    fmt.Println(forToo)
}
Task: Hofstadter Figure-Figure sequences


C++: #include <iomanip>
#include <iostream>
#include <set>
#include <vector>

using namespace std;

unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
    auto n = rlistSize > slistSize ? rlistSize : slistSize;
    auto rlist = new vector<unsigned> { 1, 3, 7 };
    auto slist = new vector<unsigned> { 2, 4, 5, 6 };
    auto list = rlistSize > 0 ? rlist : slist;
    auto target_size = rlistSize > 0 ? rlistSize : slistSize;

    while (list->size() > target_size) list->pop_back();

    while (list->size() < target_size)
    {
        auto lastIndex = rlist->size() - 1;
        auto lastr = (*rlist)[lastIndex];
        auto r = lastr + (*slist)[lastIndex];
        rlist->push_back(r);
        for (auto s = lastr + 1; s < r && list->size() < target_size;)
            slist->push_back(s++);
    }

    auto v = (*list)[n - 1];
    delete rlist;
    delete slist;
    return v;
}

ostream& operator<<(ostream& os, const set<unsigned>& s)
{
    cout << '(' << s.size() << "):";
    auto i = 0;
    for (auto c = s.begin(); c != s.end();)
    {
        if (i++ % 20 == 0) os << endl;
        os << setw(5) << *c++;
    }
    return os;
}

int main(int argc, const char* argv[])
{
    const auto v1 = atoi(argv[1]);
    const auto v2 = atoi(argv[2]);
    set<unsigned> r, s;
    for (auto n = 1; n <= v2; n++)
    {
        if (n <= v1)
            r.insert(hofstadter(n, 0));
        s.insert(hofstadter(0, n));
    }
    cout << "R" << r << endl;
    cout << "S" << s << endl;

    int m = max(*r.rbegin(), *s.rbegin());
    for (auto n = 1; n <= m; n++)
        if (r.count(n) == s.count(n))
            clog << "integer " << n << " either in both or neither set" << endl;

    return 0;
}



Go: package main

import "fmt"

var ffr, ffs func(int) int




func init() {
    
    r := []int{0, 1}
    s := []int{0, 2}

    ffr = func(n int) int {
        for len(r) <= n {
            nrk := len(r) - 1       
            rNxt := r[nrk] + s[nrk] 
            r = append(r, rNxt)     
            for sn := r[nrk] + 2; sn < rNxt; sn++ {
                s = append(s, sn)   
            }
            s = append(s, rNxt+1)   
        }
        return r[n]
    }

    ffs = func(n int) int {
        for len(s) <= n {
            ffr(len(r))
        }
        return s[n]
    }
}

func main() {
    
    for n := 1; n <= 10; n++ {
        fmt.Printf("r(%d): %d\n", n, ffr(n))
    }
    
    var found [1001]int
    for n := 1; n <= 40; n++ {
        found[ffr(n)]++
    }
    for n := 1; n <= 960; n++ {
        found[ffs(n)]++
    }
    for i := 1; i <= 1000; i++ {
        if found[i] != 1 {
            fmt.Println("task 4: FAIL")
            return
        }
    }
    fmt.Println("task 4: PASS")
}
Task: Magic squares of odd order


C++: #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
 
class MagicSquare
{
public: 
    MagicSquare(int d) : sqr(d*d,0), sz(d)
    {
        assert(d&1);
        fillSqr();
    }
 
    void display()
    {
        cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
        cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
        ostringstream cvr;
        cvr << sz * sz;
        int l = cvr.str().size();
 
	for( int y = 0; y < sz; y++ )
	{
	    int yy = y * sz;
	    for( int x = 0; x < sz; x++ )
		cout << setw( l + 2 ) << sqr[yy + x];
	    cout << "\n";
	}
        cout << "\n\n";
    }
 
private:
    void fillSqr()
    {
	int sx = sz / 2, sy = 0, c = 0;
	while( c < sz * sz )
	{
	    if( !sqr[sx + sy * sz] )
	    {
		sqr[sx + sy * sz]= c + 1;
		inc( sx ); dec( sy ); 
		c++;
	    }
	    else
	    {
		dec( sx ); inc( sy ); inc( sy );
	    }
	}
    }
 
    int magicNumber()
    { return sz * ( ( sz * sz ) + 1 ) / 2; }
 
    void inc( int& a )
    { if( ++a == sz ) a = 0; }
 
    void dec( int& a )
    { if( --a < 0 ) a = sz - 1; }
 
    bool checkPos( int x, int y )
    { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
 
    bool isInside( int s )
    { return ( s < sz && s > -1 ); }
 
    vector<int> sqr;
    int sz;
};
 
int main()
{
    MagicSquare s(7);
    s.display();
    return 0;
}



Go: package main

import (
    "fmt"
    "log"
)

func ms(n int) (int, []int) {
    M := func(x int) int { return (x + n - 1) % n }
    if n <= 0 || n&1 == 0 {
        n = 5
        log.Println("forcing size", n)
    }
    m := make([]int, n*n)
    i, j := 0, n/2
    for k := 1; k <= n*n; k++ {
        m[i*n+j] = k
        if m[M(i)*n+M(j)] != 0 {
            i = (i + 1) % n
        } else {
            i, j = M(i), M(j)
        }
    }
    return n, m
}

func main() {
    n, m := ms(5)
    i := 2
    for j := 1; j <= n*n; j *= 10 {
        i++
    }
    f := fmt.Sprintf("%%%dd", i)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            fmt.Printf(f, m[i*n+j])
        }
        fmt.Println()
    }
}
Task: Yellowstone sequence


C++: #include <iostream>
#include <numeric>
#include <set>

template <typename integer>
class yellowstone_generator {
public:
    integer next() {
        n2_ = n1_;
        n1_ = n_;
        if (n_ < 3) {
            ++n_;
        } else {
            for (n_ = min_; !(sequence_.count(n_) == 0
                && std::gcd(n1_, n_) == 1
                && std::gcd(n2_, n_) > 1); ++n_) {}
        }
        sequence_.insert(n_);
        for (;;) {
            auto it = sequence_.find(min_);
            if (it == sequence_.end())
                break;
            sequence_.erase(it);
            ++min_;
        }
        return n_;
    }
private:
    std::set<integer> sequence_;
    integer min_ = 1;
    integer n_ = 0;
    integer n1_ = 0;
    integer n2_ = 0;
};

int main() {
    std::cout << "First 30 Yellowstone numbers:\n";
    yellowstone_generator<unsigned int> ygen;
    std::cout << ygen.next();
    for (int i = 1; i < 30; ++i)
        std::cout << ' ' << ygen.next();
    std::cout << '\n';
    return 0;
}



Go: package main

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

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

func yellowstone(n int) []int {
    m := make(map[int]bool)
    a := make([]int, n+1)
    for i := 1; i < 4; i++ {
        a[i] = i
        m[i] = true
    }
    min := 4
    for c := 4; c <= n; c++ {
        for i := min; ; i++ {
            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
                a[c] = i
                m[i] = true
                if i == min {
                    min++
                }
                break
            }
        }
    }    
    return a[1:]
}

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

func main() {
    x := make([]int, 100)
    for i := 0; i < 100; i++ {
        x[i] = i + 1
    }
    y := yellowstone(100)
    fmt.Println("The first 30 Yellowstone numbers are:")
    fmt.Println(y[:30])
    g := exec.Command("gnuplot", "-persist")
    w, err := g.StdinPipe()
    check(err)
    check(g.Start())
    fmt.Fprintln(w, "unset key; plot '-'")
    for i, xi := range x {
        fmt.Fprintf(w, "%d %d\n", xi, y[i])
    }
    fmt.Fprintln(w, "e")
    w.Close()
    g.Wait()
}
Task: Mertens function


C++: #include <iomanip>
#include <iostream>
#include <vector>

std::vector<int> mertens_numbers(int max) {
    std::vector<int> m(max + 1, 1);
    for (int n = 2; n <= max; ++n) {
        for (int k = 2; k <= n; ++k)
            m[n] -= m[n / k];
    }
    return m;
}

int main() {
    const int max = 1000;
    auto m(mertens_numbers(max));
    std::cout << "First 199 Mertens numbers:\n";
    for (int i = 0, column = 0; i < 200; ++i) {
        if (column > 0)
            std::cout << ' ';
        if (i == 0)
            std::cout << "  ";
        else
            std::cout << std::setw(2) << m[i];
        ++column;
        if (column == 20) {
            std::cout << '\n';
            column = 0;
        }
    }
    int zero = 0, cross = 0, previous = 0;
    for (int i = 1; i <= max; ++i) {
        if (m[i] == 0) {
            ++zero;
            if (previous != 0)
                ++cross;
        }
        previous = m[i];
    }
    std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
    std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
    return 0;
}



Go: package main

import "fmt"

func mertens(to int) ([]int, int, int) {
    if to < 1 {
        to = 1
    }
    merts := make([]int, to+1)
    primes := []int{2}
    var sum, zeros, crosses int
    for i := 1; i <= to; i++ {
        j := i
        cp := 0      
        spf := false 
        for _, p := range primes {
            if p > j {
                break
            }
            if j%p == 0 {
                j /= p
                cp++
            }
            if j%p == 0 {
                spf = true
                break
            }
        }
        if cp == 0 && i > 2 {
            cp = 1
            primes = append(primes, i)
        }
        if !spf {
            if cp%2 == 0 {
                sum++
            } else {
                sum--
            }
        }
        merts[i] = sum
        if sum == 0 {
            zeros++
            if i > 1 && merts[i-1] != 0 {
                crosses++
            }
        }
    }
    return merts, zeros, crosses
}

func main() {
    merts, zeros, crosses := mertens(1000)
    fmt.Println("Mertens sequence - First 199 terms:")
    for i := 0; i < 200; i++ {
        if i == 0 {
            fmt.Print("    ")
            continue
        }
        if i%20 == 0 {
            fmt.Println()
        }
        fmt.Printf("  % d", merts[i])
    }
    fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
    fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
}
Task: Order by pair comparisons


C++: #include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

bool InteractiveCompare(const string& s1, const string& s2)
{
    if(s1 == s2) return false;  
    static int count = 0;
    string response;
    cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
    getline(cin, response);
    return !response.empty() && response.front() == 'y';
}

void PrintOrder(const vector<string>& items)
{
    cout << "{ ";
    for(auto& item : items) cout << item << " ";
    cout << "}\n";
}

int main()
{
    const vector<string> items
    {
        "violet", "red", "green", "indigo", "blue", "yellow", "orange"
    };
    
    vector<string> sortedItems;
    
    
    
    for(auto& item : items)
    {
        cout << "Inserting '" << item << "' into ";
        PrintOrder(sortedItems);
        
        
        auto spotToInsert = lower_bound(sortedItems.begin(),
                                        sortedItems.end(), item, InteractiveCompare);
        sortedItems.insert(spotToInsert, item);
    }
    PrintOrder(sortedItems);
    return 0;
}



Go: package main
 
import (
    "fmt"
    "sort"
    "strings"
)

var count int = 0

func interactiveCompare(s1, s2 string) bool {
    count++
    fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
    var response string
    _, err := fmt.Scanln(&response)
    return err == nil && strings.HasPrefix(response, "y")
}

func main() {
    items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
    
    var sortedItems []string
    
    
    
    for _, item := range items {
        fmt.Printf("Inserting '%s' into %s\n", item, sortedItems)
        
        
        spotToInsert := sort.Search(len(sortedItems), func(i int) bool {
            return interactiveCompare(item, sortedItems[i])
        })
        sortedItems = append(sortedItems[:spotToInsert],
                             append([]string{item}, sortedItems[spotToInsert:]...)...)
    }
    fmt.Println(sortedItems)
}
Task: Benford's law


C++: 

#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;

class NextNum {
public :
   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
   cl_I operator( )( ) {
      cl_I result = first + second ;
      first = second ;
      second = result ;
      return result ;
   }
private :
   cl_I first ;
   cl_I second ;
} ;

void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {
   for ( cl_I bignumber : fibos ) {
      std::ostringstream os ;
      fprintdecimal ( os , bignumber ) ;
      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
      if ( ! result.second ) 
	 numberfrequencies[ firstdigit ]++ ;
   }
}

int main( ) {
   std::vector<cl_I> fibonaccis( 1000 ) ;
   fibonaccis[ 0 ] = 0 ;
   fibonaccis[ 1 ] = 1 ;
   cl_I a = 0 ;
   cl_I b = 1 ;
   
   
   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
   std::cout << std::endl ;
   std::map<int , int> frequencies ;
   findFrequencies( fibonaccis , frequencies ) ;
   std::cout << "                found                    expected\n" ;
   for ( int i = 1 ; i < 10 ; i++ ) {
      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
      std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
      std::cout.precision( 3 ) ;
      std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
   }
   return 0 ;
}



Go: package main

import (
    "fmt"
    "math"
)

func Fib1000() []float64 {
    a, b, r := 0., 1., [1000]float64{}
    for i := range r {
        r[i], a, b = b, b, b+a
    }
    return r[:]
}

func main() {
    show(Fib1000(), "First 1000 Fibonacci numbers")
}

func show(c []float64, title string) {
    var f [9]int
    for _, v := range c {
        f[fmt.Sprintf("%g", v)[0]-'1']++
    }
    fmt.Println(title)
    fmt.Println("Digit  Observed  Predicted")
    for i, n := range f {
        fmt.Printf("  %d  %9.3f  %8.3f\n", i+1, float64(n)/float64(len(c)),
            math.Log10(1+1/float64(i+1)))
    }
}
Task: Nautical bell


C++: #include <iostream>
#include <string>
#include <windows.h>


using namespace std;


class bells
{
public:
    void start()
    {
	watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] =  "First"; 
	count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
	_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
    }
private:
    static DWORD WINAPI bell( LPVOID p )
    {
	DWORD wait = _inst->waitTime();
	while( true )
	{
	    Sleep( wait );
	    _inst->playBell();
	    wait = _inst->waitTime();
	}
	return 0;
    }

    DWORD waitTime() 
    { 
	GetLocalTime( &st );
	int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
	return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
    }

    void playBell()
    {
	GetLocalTime( &st );
	int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
	int w = ( 60 * st.wHour + st.wMinute ); 
	if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
	char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );

	cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
	if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;

	for( int x = 0, c = 1; x < b; x++, c++ )
	{
	    cout << "\7"; Sleep( 500 );
	    if( !( c % 2 ) ) Sleep( 300 );
	}
    }

    SYSTEMTIME st;
    string watch[7], count[8];
    static bells* _inst;
};

bells* bells::_inst = 0;

int main( int argc, char* argv[] )
{
    bells b; b.start();
    while( 1 ); 
    return 0;
}




Go: package main

import (
    "fmt"
    "strings"
    "time"
)

func main() {
    watches := []string{
        "First", "Middle", "Morning", "Forenoon",
        "Afternoon", "Dog", "First",
    }
    for {
        t := time.Now()
        h := t.Hour()
        m := t.Minute()
        s := t.Second()
        if (m == 0 || m == 30) && s == 0 {
            bell := 0
            if m == 30 {
                bell = 1
            }
            bells := (h*2 + bell) % 8
            watch := h/4 + 1
            if bells == 0 {
                bells = 8
                watch--
            }
            sound := strings.Repeat("\a", bells)
            pl := "s"
            if bells == 1 {
                pl = " "
            }
            w := watches[watch] + " watch"
            if watch == 5 {
                if bells < 5 {
                    w = "First " + w
                } else {
                    w = "Last " + w
                }
            }
            fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
        }
        time.Sleep(1 * time.Second)
    }
}
Task: Anonymous recursion


C++: double fib(double n)
{
  if(n < 0)
  {
    throw "Invalid argument passed to fib";
  }
  else
  {
    struct actual_fib
    {
        static double calc(double n)
        {
          if(n < 2)
          {
            return n;
          }
          else
          {
            return calc(n-1) + calc(n-2);
          }
        }
    };

    return actual_fib::calc(n);
  }
}



Go: package main

import "fmt"

func main() {
    for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
        f, ok := arFib(n)
        if ok {
            fmt.Printf("fib %d = %d\n", n, f)
        } else {
            fmt.Println("fib undefined for negative numbers")
        }
    }
}

func arFib(n int) (int, bool) {
    switch {
    case n < 0:
        return 0, false
    case n < 2:
        return n, true
    }
    return yc(func(recurse fn) fn {
        return func(left, term1, term2 int) int {
            if left == 0 {
                return term1+term2
            }
            return recurse(left-1, term1+term2, term1)
        }
    })(n-2, 1, 0), true
}

type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn

func yc(f ff) fn {
    return func(x fx) fn {
        return x(x)
    }(func(x fx) fn {
        return f(func(a1, a2, a3 int) int {
            return x(x)(a1, a2, a3)
        })
    })
}
Task: Substring_Top and tail


C++: #include <string>
#include <iostream>

int main( ) {
   std::string word( "Premier League" ) ;
   std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
   std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
   std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
   return 0 ;
}



Go: package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    
    s := "ASCII"
    fmt.Println("String:                ", s)
    fmt.Println("First byte removed:    ", s[1:])
    fmt.Println("Last byte removed:     ", s[:len(s)-1])
    fmt.Println("First and last removed:", s[1:len(s)-1])
    
    u := "Δημοτική"
    fmt.Println("String:                ", u)
    _, sizeFirst := utf8.DecodeRuneInString(u)
    fmt.Println("First rune removed:    ", u[sizeFirst:])
    _, sizeLast := utf8.DecodeLastRuneInString(u)
    fmt.Println("Last rune removed:     ", u[:len(u)-sizeLast])
    fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
Task: Legendre prime counting function


C++: #include <cmath>
#include <iostream>
#include <vector>

std::vector<int> generate_primes(int limit) {
    std::vector<bool> sieve(limit >> 1, true);
    for (int p = 3, s = 9; s < limit; p += 2) {
        if (sieve[p >> 1]) {
            for (int q = s; q < limit; q += p << 1)
                sieve[q >> 1] = false;
        }
        s += (p + 1) << 2;
    }
    std::vector<int> primes;
    if (limit > 2)
        primes.push_back(2);
    for (int i = 1; i < sieve.size(); ++i) {
        if (sieve[i])
            primes.push_back((i << 1) + 1);
    }
    return primes;
}

class legendre_prime_counter {
public:
    explicit legendre_prime_counter(int limit);
    int prime_count(int n);
private:
    int phi(int x, int a);
    std::vector<int> primes;
};

legendre_prime_counter::legendre_prime_counter(int limit) :
    primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}

int legendre_prime_counter::prime_count(int n) {
    if (n < 2)
        return 0;
    int a = prime_count(static_cast<int>(std::sqrt(n)));
    return phi(n, a) + a - 1;
}

int legendre_prime_counter::phi(int x, int a) {
    if (a == 0)
        return x;
    if (a == 1)
        return x - (x >> 1);
    int pa = primes[a - 1];
    if (x <= pa)
        return 1;
    return phi(x, a - 1) - phi(x / pa, a - 1);
}

int main() {
    legendre_prime_counter counter(1000000000);
    for (int i = 0, n = 1; i < 10; ++i, n *= 10)
        std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}



Go: package main

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

func cantorPair(x, y int) int {
    if x < 0 || y < 0 {
        log.Fatal("Arguments must be non-negative integers.")
    }
    return (x*x + 3*x + 2*x*y + y + y*y) / 2
}

func pi(n int) int {
    if n < 2 {
        return 0
    }
    if n == 2 {
        return 1
    }
    primes := rcu.Primes(int(math.Sqrt(float64(n))))
    a := len(primes)
    memoPhi := make(map[int]int)

    var phi func(x, a int) int 
    phi = func(x, a int) int {
        if a < 1 {
            return x
        }
        if a == 1 {
            return x - (x >> 1)
        }
        pa := primes[a-1]
        if x <= pa {
            return 1
        }
        key := cantorPair(x, a)
        if v, ok := memoPhi[key]; ok {
            return v
        }
        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)
        return memoPhi[key]
    }

    return phi(n, a) + a - 1
}

func main() {
    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {
        fmt.Printf("10^%d  %d\n", i, pi(n))
    }
}
Task: Use another language to call a function


C++: #include <string>
using std::string;


extern "C" int
Query (char *Data, size_t *Length)
{
   const string Message = "Here am I";

   
   if (*Length < Message.length())
      return false;  

   *Length = Message.length();
   Message.copy(Data, *Length);
   return true;
}



Go: package main



import "C"
import "unsafe"

func main() {
    C.Run()
}

const msg = "Here am I"


func Query(cbuf *C.char, csiz *C.size_t) C.int {
    if int(*csiz) <= len(msg) {
        return 0
    }
    pbuf := uintptr(unsafe.Pointer(cbuf))
    for i := 0; i < len(msg); i++ {
        *((*byte)(unsafe.Pointer(pbuf))) = msg[i]
        pbuf++
    }
    *((*byte)(unsafe.Pointer(pbuf))) = 0
    *csiz = C.size_t(len(msg) + 1)
    return 1
}