WeixiangYan/CodeTransOcean huggingface dataset:
Task: Longest string challenge


C++: #include <iostream>
#include <string.h>
 
int main()
{
    std::string longLine, longestLines, newLine;

    while (std::cin >> newLine)
    {
        auto isNewLineShorter = longLine.c_str();
        auto isLongLineShorter = newLine.c_str(); 
        while (*isNewLineShorter && *isLongLineShorter)
        {
            
            
            
            isNewLineShorter = &isNewLineShorter[1];
            isLongLineShorter = &isLongLineShorter[1];
        }

        if(*isNewLineShorter) continue; 
        if(*isLongLineShorter)
        {
            
            longLine = newLine;
            longestLines = newLine;
        }
        else
        {
            
            longestLines+=newLine; 
        }
        longestLines+="\n"; 
    }

    std::cout << "\nLongest string:\n" << longestLines;
}



Go: package main

import (
    "bufio"
    "os"
)

func main() {
    in := bufio.NewReader(os.Stdin)
    var blankLine = "\n"
    var printLongest func(string) string
    printLongest = func(candidate string) (longest string) {
        longest = candidate
        s, err := in.ReadString('\n')
        defer func() {
            recover()
            defer func() {
                recover()
            }()
            _ = blankLine[0]
            func() {
                defer func() {
                    recover()
                }()
                _ = s[len(longest)]
                longest = s
            }()
            longest = printLongest(longest)
            func() {
                defer func() {
                    recover()
                    os.Stdout.WriteString(s)
                }()
                _ = longest[len(s)]
                s = ""
            }()
        }()
        _ = err.(error)
        os.Stdout.WriteString(blankLine)
        blankLine = ""
        return
    }
    printLongest("")
}
Task: Create a file


C++: #include <direct.h>
#include <fstream>

int main() {
    std::fstream f("output.txt", std::ios::out);
    f.close();
    f.open("/output.txt", std::ios::out);
    f.close();

    _mkdir("docs");
    _mkdir("/docs");

    return 0;
}



Go: package main

import (
    "fmt"
    "os"
)

func createFile(fn string) {
    f, err := os.Create(fn)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("file", fn, "created!")
    f.Close()
}

func createDir(dn string) {
    err := os.Mkdir(dn, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("directory", dn, "created!")
}

func main() {
    createFile("input.txt")
    createFile("/input.txt")
    createDir("docs")
    createDir("/docs")
}
Task: Chernick's Carmichael numbers


C++: #include <gmp.h>
#include <iostream>

using namespace std;

typedef unsigned long long int u64;

bool primality_pretest(u64 k) {     

    if (!(k %  3) || !(k %  5) || !(k %  7) || !(k % 11) ||
        !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)
    ) {
        return (k <= 23);
    }

    return true;
}

bool probprime(u64 k, mpz_t n) {
    mpz_set_ui(n, k);
    return mpz_probab_prime_p(n, 0);
}

bool is_chernick(int n, u64 m, mpz_t z) {

    if (!primality_pretest(6 * m + 1)) {
        return false;
    }

    if (!primality_pretest(12 * m + 1)) {
        return false;
    }

    u64 t = 9 * m;

    for (int i = 1; i <= n - 2; i++) {
        if (!primality_pretest((t << i) + 1)) {
            return false;
        }
    }

    if (!probprime(6 * m + 1, z)) {
        return false;
    }

    if (!probprime(12 * m + 1, z)) {
        return false;
    }

    for (int i = 1; i <= n - 2; i++) {
        if (!probprime((t << i) + 1, z)) {
            return false;
        }
    }

    return true;
}

int main() {

    mpz_t z;
    mpz_inits(z, NULL);

    for (int n = 3; n <= 10; n++) {

        
        u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;

        
        if (n > 5) {
            multiplier *= 5;
        }

        for (u64 k = 1; ; k++) {

            u64 m = k * multiplier;

            if (is_chernick(n, m, z)) {
                cout << "a(" << n << ") has m = " << m << endl;
                break;
            }
        }
    }

    return 0;
}



Go: package main

import (
    "fmt"
    "math/big"
)

var (
    zero = new(big.Int)
    prod = new(big.Int)
    fact = new(big.Int)
)

func ccFactors(n, m uint64) (*big.Int, bool) {
    prod.SetUint64(6*m + 1)
    if !prod.ProbablyPrime(0) {
        return zero, false
    }
    fact.SetUint64(12*m + 1)
    if !fact.ProbablyPrime(0) { 
        return zero, false
    }
    prod.Mul(prod, fact)
    for i := uint64(1); i <= n-2; i++ {
        fact.SetUint64((1<<i)*9*m + 1)
        if !fact.ProbablyPrime(0) {
            return zero, false
        }
        prod.Mul(prod, fact)
    }
    return prod, true
}

func ccNumbers(start, end uint64) {
    for n := start; n <= end; n++ {
        m := uint64(1)
        if n > 4 {
            m = 1 << (n - 4)
        }
        for {
            num, ok := ccFactors(n, m)
            if ok {
                fmt.Printf("a(%d) = %d\n", n, num)
                break
            }
            if n <= 4 {
                m++
            } else {
                m += 1 << (n - 4)
            }
        }
    }
}

func main() {
    ccNumbers(3, 9)
}
Task: Tau function


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


unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    
    for (; (n & 1) == 0; n >>= 1)
        ++total;
    
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p)
            ++count;
        total *= count;
    }
    
    if (n > 1)
        total *= 2;
    return total;
}

int main() {
    const unsigned int limit = 100;
    std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
    for (unsigned int n = 1; n <= limit; ++n) {
        std::cout << std::setw(3) << divisor_count(n);
        if (n % 20 == 0)
            std::cout << '\n';
    }
}



Go: package main

import "fmt"

func countDivisors(n int) int {
    count := 0
    i := 1
    k := 2
    if n%2 == 0 {
        k = 1
    }
    for i*i <= n {
        if n%i == 0 {
            count++
            j := n / i
            if j != i {
                count++
            }
        }
        i += k
    }
    return count
}

func main() {
    fmt.Println("The tau functions for the first 100 positive integers are:")
    for i := 1; i <= 100; i++ {
        fmt.Printf("%2d  ", countDivisors(i))
        if i%20 == 0 {
            fmt.Println()
        }
    }
}
Task: Create an object at a given address


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

int main()
{
    
    char* data = new char[sizeof(std::string)];

    
    std::string* stringPtr = new (data) std::string("ABCD");

    std::cout << *stringPtr << " 0x" << stringPtr << std::endl;

    
    
    stringPtr->~basic_string();
    stringPtr = new (data) std::string("123456");

    std::cout << *stringPtr << " 0x" << stringPtr << std::endl;

    
    stringPtr->~basic_string();
    delete[] data;
}



Go: package main

import(
	"fmt"
	"unsafe"
	"reflect"
)

func pointer() {
	fmt.Printf("Pointer:\n")

	
	
	
	
	var i int
	p := &i

	fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)

	*p = 3

	fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}

func slice() {
	fmt.Printf("Slice:\n")

	var a [10]byte

	
	
	
	
	
	var h reflect.SliceHeader
	h.Data = uintptr(unsafe.Pointer(&a)) 
	h.Len = len(a)
	h.Cap = len(a)

	
	s := *(*[]byte)(unsafe.Pointer(&h))

	fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)

	
	
	copy(s, "A string.")

	fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}

func main() {
	pointer()
	fmt.Println()

	slice()
}
Task: Sequence of primorial primes


C++: #include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>

typedef mpz_class integer;

bool is_probably_prime(const integer& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

int main() {
    const unsigned int max = 20;
    integer primorial = 1;
    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {
        if (!is_prime(p))
            continue;
        primorial *= p;
        ++index;
        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {
            if (count > 0)
                std::cout << ' ';
            std::cout << index;
            ++count;
        }
    }
    std::cout << '\n';
    return 0;
}



Go: package main
  
import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewInt(1)
    pm := big.NewInt(1) 
    var px, nx int
    var pb big.Int 
    primes(4000, func(p int64) bool {
        pm.Mul(pm, pb.SetInt64(p))
        px++
        if pb.Add(pm, one).ProbablyPrime(0) ||
            pb.Sub(pm, one).ProbablyPrime(0) {
            fmt.Print(px, " ")
            nx++
            if nx == 20 {
                fmt.Println()
                return false
            }
        }
        return true
    })
}




func primes(limit int, f func(int64) bool) {
    c := make([]bool, limit)
    c[0] = true
    c[1] = true
    lm := int64(limit)
    p := int64(2)
    for {
        f(p)
        p2 := p * p
        if p2 >= lm {
            break
        }
        for i := p2; i < lm; i += p {
            c[i] = true
        }
        for {
            p++
            if !c[p] {
                break
            }
        }
    }
    for p++; p < lm; p++ {
        if !c[p] && !f(p) {
            break
        }
    }
}
Task: Factorions


C++: #include <iostream>

class factorion_t {
public:
    factorion_t() {
        f[0] = 1u;
        for (uint n = 1u; n < 12u; n++)
            f[n] = f[n - 1] * n;
    }

    bool operator()(uint i, uint b) const {
        uint sum = 0;
        for (uint j = i; j > 0u; j /= b)
            sum += f[j % b];
        return sum == i;
    }

private:
    ulong f[12];  
};

int main() {
    factorion_t factorion;
    for (uint b = 9u; b <= 12u; ++b) {
        std::cout << "factorions for base " << b << ':';
        for (uint i = 1u; i < 1500000u; ++i)
            if (factorion(i, b))
                std::cout << ' ' << i;
        std::cout << std::endl;
    }
    return 0;
}



Go: package main

import (
    "fmt"
    "strconv"
)

func main() {
    
    var fact [12]uint64
    fact[0] = 1
    for n := uint64(1); n < 12; n++ {
        fact[n] = fact[n-1] * n
    }

    for b := 9; b <= 12; b++ {
        fmt.Printf("The factorions for base %d are:\n", b)
        for i := uint64(1); i < 1500000; i++ {
            digits := strconv.FormatUint(i, b)
            sum := uint64(0)
            for _, digit := range digits {
                if digit < 'a' {
                    sum += fact[digit-'0']
                } else {
                    sum += fact[digit+10-'a']
                }
            }
            if sum == i {
                fmt.Printf("%d ", i)
            }
        }
        fmt.Println("\n")
    }
}
Task: Sorting algorithms_Strand sort


C++: #include <list>

template <typename T>
std::list<T> strandSort(std::list<T> lst) {
  if (lst.size() <= 1)
    return lst;
  std::list<T> result;
  std::list<T> sorted;
  while (!lst.empty()) {
    sorted.push_back(lst.front());
    lst.pop_front();
    for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {
      if (sorted.back() <= *it) {
        sorted.push_back(*it);
        it = lst.erase(it);
      } else
        it++;
    }
    result.merge(sorted);
  }
  return result;
}



Go: package main

import "fmt"

type link struct {
    int
    next *link
}

func linkInts(s []int) *link {
    if len(s) == 0 {
        return nil
    }
    return &link{s[0], linkInts(s[1:])}
}

func (l *link) String() string {
    if l == nil {
        return "nil"
    }
    r := fmt.Sprintf("[%d", l.int)
    for l = l.next; l != nil; l = l.next {
        r = fmt.Sprintf("%s %d", r, l.int)
    }
    return r + "]"
}

func main() {
    a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})
    fmt.Println("before:", a)
    b := strandSort(a)
    fmt.Println("after: ", b)
}

func strandSort(a *link) (result *link) {
    for a != nil {
        
        sublist := a
        a = a.next
        sTail := sublist
        for p, pPrev := a, a; p != nil; p = p.next {
            if p.int > sTail.int {
                
                sTail.next = p
                sTail = p
                
                if p == a {
                    a = p.next
                } else {
                    pPrev.next = p.next
                }
            } else {
                pPrev = p
            }
        }
        sTail.next = nil 
        if result == nil {
            result = sublist
            continue
        }
        
        var m, rr *link
        if sublist.int < result.int {
            m = sublist
            sublist = m.next
            rr = result
        } else {
            m = result
            rr = m.next
        }
        result = m
        for {
            if sublist == nil {
                m.next = rr
                break
            }
            if rr == nil {
                m.next = sublist
                break
            }
            if sublist.int < rr.int {
                m.next = sublist
                m = sublist
                sublist = m.next
            } else {
                m.next = rr
                m = rr
                rr = m.next
            }
        }
    }
    return
}
Task: Additive primes


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

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

unsigned int digit_sum(unsigned int n) {
    unsigned int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int main() {
    const unsigned int limit = 500;
    std::cout << "Additive primes less than " << limit << ":\n";
    unsigned int count = 0;
    for (unsigned int n = 1; n < limit; ++n) {
        if (is_prime(digit_sum(n)) && is_prime(n)) {
            std::cout << std::setw(3) << n;
            if (++count % 10 == 0)
                std::cout << '\n';
            else
                std::cout << ' ';
        }
    }
    std::cout << '\n' << count << " additive primes found.\n";
}



Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func sumDigits(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func main() {
    fmt.Println("Additive primes less than 500:")
    i := 2
    count := 0
    for {
        if isPrime(i) && isPrime(sumDigits(i)) {
            count++
            fmt.Printf("%3d  ", i)
            if count%10 == 0 {
                fmt.Println()
            }
        }
        if i > 2 {
            i += 2
        } else {
            i++
        }
        if i > 499 {
            break
        }
    }
    fmt.Printf("\n\n%d additive primes found.\n", count)
}
Task: Inverted syntax


C++: class invertedAssign {
  int data;
public:
  invertedAssign(int data):data(data){}
  int getData(){return data;}
  void operator=(invertedAssign& other) const {
    other.data = this->data;
  }
};


#include <iostream>

int main(){
  invertedAssign a = 0;
  invertedAssign b = 42;
  std::cout << a.getData() << ' ' << b.getData() << '\n';

  b = a;

  std::cout << a.getData() << ' ' << b.getData() << '\n';
}



Go: package main

import "fmt"

type ibool bool

const itrue ibool = true

func (ib ibool) iif(cond bool) bool {
    if cond {
        return bool(ib)
    }
    return bool(!ib)
}

func main() {
    var needUmbrella bool
    raining := true

    
    if raining {
        needUmbrella = true
    }
    fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)

    
    raining = false
    needUmbrella = itrue.iif(raining)
    fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
Task: Perfect totient numbers


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

class totient_calculator {
public:
    explicit totient_calculator(int max) : totient_(max + 1) {
        for (int i = 1; i <= max; ++i)
            totient_[i] = i;
        for (int i = 2; i <= max; ++i) {
            if (totient_[i] < i)
                continue;
            for (int j = i; j <= max; j += i)
                totient_[j] -= totient_[j] / i;
        }
    }
    int totient(int n) const {
        assert (n >= 1 && n < totient_.size());
        return totient_[n];
    }
    bool is_prime(int n) const {
        return totient(n) == n - 1;
    }
private:
    std::vector<int> totient_;
};

bool perfect_totient_number(const totient_calculator& tc, int n) {
    int sum = 0;
    for (int m = n; m > 1; ) {
        int t = tc.totient(m);
        sum += t;
        m = t;
    }
    return sum == n;
}

int main() {
    totient_calculator tc(10000);
    int count = 0, n = 1;
    std::cout << "First 20 perfect totient numbers:\n";
    for (; count < 20; ++n) {
        if (perfect_totient_number(tc, n))  {
            if (count > 0)
                std::cout << ' ';
            ++count;
            std::cout << n;
        }
    }
    std::cout << '\n';
    return 0;
}



Go: package main

import "fmt"

func gcd(n, k int) int {
    if n < k || k < 1 {
        panic("Need n >= k and k >= 1")
    }

    s := 1
    for n&1 == 0 && k&1 == 0 {
        n >>= 1
        k >>= 1
        s <<= 1
    }

    t := n
    if n&1 != 0 {
        t = -k
    }
    for t != 0 {
        for t&1 == 0 {
            t >>= 1
        }
        if t > 0 {
            n = t
        } else {
            k = -t
        }
        t = n - k
    }
    return n * s
}

func totient(n int) int {
    tot := 0
    for k := 1; k <= n; k++ {
        if gcd(n, k) == 1 {
            tot++
        }
    }
    return tot
}

func main() {
    var perfect []int
    for n := 1; len(perfect) < 20; n += 2 {
        tot := n
        sum := 0
        for tot != 1 {
            tot = totient(tot)
            sum += tot
        }
        if sum == n {
            perfect = append(perfect, n)
        }
    }
    fmt.Println("The first 20 perfect totient numbers are:")
    fmt.Println(perfect)
}
Task: Delegates


C++: #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>

using namespace std;
using namespace std::tr1;
using std::tr1::function;


class IDelegate
{
public:
    virtual ~IDelegate() {}
};


class IThing
{
public:
    virtual ~IThing() {}
    virtual std::string Thing() = 0;
};


class DelegateA : virtual public IDelegate
{
};
 

class DelegateB : public IThing, public IDelegate
{
    std::string Thing()
    {
        return "delegate implementation";
    }
};
 
class Delegator
{
public:
    std::string Operation()
    {
        if(Delegate) 
           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
            
            return pThing->Thing();
        
        return "default implementation";
    }
 
    shared_ptr<IDelegate> Delegate;
};
 
int main()
{
    shared_ptr<DelegateA> delegateA(new DelegateA());
    shared_ptr<DelegateB> delegateB(new DelegateB());
    Delegator delegator;
 
    
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateA;
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateB;
    std::cout << delegator.Operation() << std::endl;


}



Go: package main
import "fmt"

type Delegator struct {
    delegate interface{} 
}


type Thingable interface {
    thing() string
}

func (self Delegator) operation() string {
    if v, ok := self.delegate.(Thingable); ok {
        return v.thing()
    }
    return "default implementation"
}

type Delegate int 

func (Delegate) thing() string {
    return "delegate implementation"
}

func main() {
    
    a := Delegator{}
    fmt.Println(a.operation()) 

    
    a.delegate = "A delegate may be any object"
    fmt.Println(a.operation()) 

    
    var d Delegate
    a.delegate = d
    fmt.Println(a.operation()) 
}
Task: Sum of divisors


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


unsigned int divisor_sum(unsigned int n) {
    unsigned int total = 1, power = 2;
    
    for (; (n & 1) == 0; power <<= 1, n >>= 1)
        total += power;
    
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int sum = 1;
        for (power = p; n % p == 0; power *= p, n /= p)
            sum += power;
        total *= sum;
    }
    
    if (n > 1)
        total *= n + 1;
    return total;
}

int main() {
    const unsigned int limit = 100;
    std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
    for (unsigned int n = 1; n <= limit; ++n) {
        std::cout << std::setw(4) << divisor_sum(n);
        if (n % 10 == 0)
            std::cout << '\n';
    }
}



Go: package main

import "fmt"

func sumDivisors(n int) int {
    sum := 0
    i := 1
    k := 2
    if n%2 == 0 {
        k = 1
    }
    for i*i <= n {
        if n%i == 0 {
            sum += i
            j := n / i
            if j != i {
                sum += j
            }
        }
        i += k
    }
    return sum
}

func main() {
    fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
    for i := 1; i <= 100; i++ {
        fmt.Printf("%3d   ", sumDivisors(i))
        if i%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Enforced immutability


C++: #include <iostream>

class MyOtherClass
{
public:
  const int m_x;
  MyOtherClass(const int initX = 0) : m_x(initX) { }

};

int main()
{
  MyOtherClass mocA, mocB(7);

  std::cout << mocA.m_x << std::endl; 
  std::cout << mocB.m_x << std::endl; 

  
  

  return 0;
}



Go: package main

func main() {
    s := "immutable"
    s[0] = 'a'
}