WeixiangYan/CodeTransOcean huggingface dataset:
Task: Zumkeller numbers



C#: using System;
using System.Collections.Generic;
using System.Linq;

namespace ZumkellerNumbers {
    class Program {
        static List<int> GetDivisors(int n) {
            List<int> divs = new List<int> {
                1, n
            };
            for (int i = 2; i * i <= n; i++) {
                if (n % i == 0) {
                    int j = n / i;
                    divs.Add(i);
                    if (i != j) {
                        divs.Add(j);
                    }
                }
            }
            return divs;
        }

        static bool IsPartSum(List<int> divs, int sum) {
            if (sum == 0) {
                return true;
            }
            var le = divs.Count;
            if (le == 0) {
                return false;
            }
            var last = divs[le - 1];
            List<int> newDivs = new List<int>();
            for (int i = 0; i < le - 1; i++) {
                newDivs.Add(divs[i]);
            }
            if (last > sum) {
                return IsPartSum(newDivs, sum);
            }
            return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);
        }

        static bool IsZumkeller(int n) {
            var divs = GetDivisors(n);
            var sum = divs.Sum();
            
            if (sum % 2 == 1) {
                return false;
            }
            
            if (n % 2 == 1) {
                var abundance = sum - 2 * n;
                return abundance > 0 && abundance % 2 == 0;
            }
            
            return IsPartSum(divs, sum / 2);
        }

        static void Main() {
            Console.WriteLine("The first 220 Zumkeller numbers are:");
            int i = 2;
            for (int count = 0; count < 220; i++) {
                if (IsZumkeller(i)) {
                    Console.Write("{0,3} ", i);
                    count++;
                    if (count % 20 == 0) {
                        Console.WriteLine();
                    }
                }
            }

            Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:");
            i = 3;
            for (int count = 0; count < 40; i += 2) {
                if (IsZumkeller(i)) {
                    Console.Write("{0,5} ", i);
                    count++;
                    if (count % 10 == 0) {
                        Console.WriteLine();
                    }
                }
            }

            Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:");
            i = 3;
            for (int count = 0; count < 40; i += 2) {
                if (i % 10 != 5 && IsZumkeller(i)) {
                    Console.Write("{0,7} ", i);
                    count++;
                    if (count % 8 == 0) {
                        Console.WriteLine();
                    }
                }
            }
        }
    }
}
Task: Markov chain text generator



C#: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MarkovChainTextGenerator {
    class Program {
        static string Join(string a, string b) {
            return a + " " + b;
        }

        static string Markov(string filePath, int keySize, int outputSize) {
            if (keySize < 1) throw new ArgumentException("Key size can't be less than 1");

            string body;
            using (StreamReader sr = new StreamReader(filePath)) {
                body = sr.ReadToEnd();
            }
            var words = body.Split();
            if (outputSize < keySize || words.Length < outputSize) {
                throw new ArgumentException("Output size is out of range");
            }

            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
            for (int i = 0; i < words.Length - keySize; i++) {
                var key = words.Skip(i).Take(keySize).Aggregate(Join);
                string value;
                if (i + keySize < words.Length) {
                    value = words[i + keySize];
                } else {
                    value = "";
                }

                if (dict.ContainsKey(key)) {
                    dict[key].Add(value);
                } else {
                    dict.Add(key, new List<string>() { value });
                }
            }

            Random rand = new Random();
            List<string> output = new List<string>();
            int n = 0;
            int rn = rand.Next(dict.Count);
            string prefix = dict.Keys.Skip(rn).Take(1).Single();
            output.AddRange(prefix.Split());

            while (true) {
                var suffix = dict[prefix];
                if (suffix.Count == 1) {
                    if (suffix[0] == "") {
                        return output.Aggregate(Join);
                    }
                    output.Add(suffix[0]);
                } else {
                    rn = rand.Next(suffix.Count);
                    output.Add(suffix[rn]);
                }
                if (output.Count >= outputSize) {
                    return output.Take(outputSize).Aggregate(Join);
                }
                n++;
                prefix = output.Skip(n).Take(keySize).Aggregate(Join);
            }
        }

        static void Main(string[] args) {
            Console.WriteLine(Markov("alice_oz.txt", 3, 200));
        }
    }
}
Task: Partition function P



C#: using System;

class Program {

    const long Lm = (long)1e18;
    const string Fm = "D18";

    
    struct LI { public long lo, ml, mh, hi, tp; }

    static void inc(ref LI d, LI s) { 
        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
        d.tp += s.tp;
    }
 
    static void dec(ref LI d, LI s) { 
        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
        d.tp -= s.tp;
    }

    static LI set(long s) { LI d;
      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }

  static string fmt(LI x) { 
    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
    return x.lo.ToString();
  }

  static LI partcount(int n) {
    var P = new LI[n + 1]; P[0] = set(1);
    for (int i = 1; i <= n; i++) {
      int k = 0, d = -2, j = i;
      LI x = set(0);
      while (true) {
        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;
        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;
      }
      P[i] = x;
    }
    return P[n];
  }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew ();
    var res = partcount(6666); sw.Stop();
    Console.Write("{0}  {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
  }
}
Task: The sieve of Sundaram



C#: using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;

class Program
{
    static string fmt(int[] a)
    {
        var sb = new System.Text.StringBuilder();
        for (int i = 0; i < a.Length; i++)
            sb.Append(string.Format("{0,5}{1}",
              a[i], i % 10 == 9 ? "\n" : " "));
        return sb.ToString();
    }

    static void Main(string[] args)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();
        sw.Stop();
        Write("The first 100 odd prime numbers:\n{0}\n",
          fmt(pr.Take(100).ToArray()));
        Write("The millionth odd prime number: {0}", pr.Last());
        Write("\n{0} ms", sw.Elapsed.TotalMilliseconds);
    }
}

class PG
{
    public static IEnumerable<int> Sundaram(int n)
    {
        
        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;
        var comps = new bool[k + 1];
        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)
            while ((t += d + 2) < k)
                comps[t] = true;
        for (; v < k; v++)
            if (!comps[v])
                yield return (v << 1) + 1;
    }
}
Task: Consecutive primes with ascending or descending differences



C#: using System.Linq;
using System.Collections.Generic;
using TG = System.Tuple<int, int>;
using static System.Console;

class Program
{
    static void Main(string[] args)
    {
        const int mil = (int)1e6;
        foreach (var amt in new int[] { 1, 2, 6, 12, 18 })
        {
            int lmt = mil * amt, lg = 0, ng, d, ld = 0;
            var desc = new string[] { "A", "", "De" };
            int[] mx = new int[] { 0, 0, 0 },
                  bi = new int[] { 0, 0, 0 },
                   c = new int[] { 2, 2, 2 };
            WriteLine("For primes up to {0:n0}:", lmt);
            var pr = PG.Primes(lmt).ToArray();
            for (int i = 0; i < pr.Length; i++)
            {
                ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;
                if (ld == d)
                    c[2 - d]++;
                else
                {
                    if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }
                    c[d] = 2;
                }
                ld = d; lg = ng;
            }
            for (int r = 0; r <= 2; r += 2)
            {
                Write("{0}scending, found run of {1} consecutive primes:\n  {2} ",
                    desc[r], mx[r] + 1, pr[bi[r]++].Item1);
                foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))
                    Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n");
            }
        }
    }
}

class PG
{
    public static IEnumerable<TG> Primes(int lim)
    {
        bool[] flags = new bool[lim + 1];
        int j = 3, lj = 2;
        for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
            if (!flags[j])
            {
                yield return new TG(j, j - lj);
                lj = j;
                for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;
            }
        for (; j <= lim; j += 2)
            if (!flags[j])
            {
                yield return new TG(j, j - lj);
                lj = j;
            }
    }
}
Task: XML validation



C#: using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Test
{
	public static void Main()
	{
		
		XmlSchemaSet sc = new XmlSchemaSet();
		sc.Add(null, "http:
		XmlReaderSettings settings = new XmlReaderSettings();
		settings.ValidationType = ValidationType.Schema;
		settings.Schemas = sc;
		settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
		
		XmlReader reader = XmlReader.Create("http:
		
		while (reader.Read()); 
		
		Console.WriteLine("The XML file is valid for the given xsd file");
	}
	
	
	private static void ValidationCallBack(object sender, ValidationEventArgs e) {
		Console.WriteLine("Validation Error: {0}", e.Message);
	}
}
Task: Metallic ratios



C#: using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
 
class Program {
 
    static BI IntSqRoot(BI v, BI res) { 
        BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
            dl = d; d = term - res; } return term; }
 
    static string doOne(int b, int digs) { 
        int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
            bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);
        bs += b * BI.Parse('1' + new string('0', digs));
        bs >>= 1; bs += 4; string st = bs.ToString();
        return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
 
    static string divIt(BI a, BI b, int digs) { 
        int al = a.ToString().Length, bl = b.ToString().Length;
        a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
        string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
 
    
    static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        string res = ""; for (int i = 0; i < x.Length; i++) res += 
            string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
 
    static void Main(string[] args) { 
        WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\  Matches Sq.Rt Calc");
        int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
            BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
            for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
            
            n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
                lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
                on = n; n = b * n + nm1; nm1 = on; }
            WriteLine("{0,4}  {1}   {2,2}    {3, 2}  {4}  {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb"
                .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); }
        
        n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
            lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
                on = n; n += nm1; nm1 = on; }
        WriteLine("\nAu to 256 digits:"); WriteLine(t);
        WriteLine("Iteration count: {0}  Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); }
}
Task: Singly-linked list_Element removal



C#: using System;
using System.Runtime.InteropServices;

static unsafe class Program
{
    ref struct LinkedListNode
    {
        public int Value;
        public LinkedListNode* Next;
        public override string ToString() => this.Value + (this.Next == null ? string.Empty : " -> " + this.Next->ToString());
    }

    static void Remove(LinkedListNode** head, LinkedListNode* entry)
    {
        
        

        LinkedListNode** indirect = head;

        
        

        while (*indirect != entry)
            indirect = &(*indirect)->Next;

        
        *indirect = entry->Next;
    }

    static void Main()
    {
        
        var head = (LinkedListNode*)Marshal.AllocHGlobal(sizeof(LinkedListNode));
        head->Value = 1;
        head->Next = (LinkedListNode*)Marshal.AllocHGlobal(sizeof(LinkedListNode));
        head->Next->Value = 2;
        head->Next->Next = null;

        LinkedListNode copy = *head;

        Console.WriteLine("original:                    " + head->ToString());

        Remove(&head, head);
        Console.WriteLine("after removing head:         " + head->ToString());

        head = &copy;
        Console.WriteLine("restored from copy:          " + head->ToString());

        Remove(&head, head->Next);
        Console.WriteLine("after removing second node:  " + head->ToString());
    }
}
Task: Data Encryption Standard



C#: using System;
using System.IO;
using System.Security.Cryptography;

namespace DES {
    class Program {
        
        static string ByteArrayToString(byte[] ba) {
            return BitConverter.ToString(ba).Replace("-", "");
        }

        
        
        static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {
            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

            
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);
            CryptoStreamMode mode = CryptoStreamMode.Write;

            
            MemoryStream memStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
            cryptoStream.Write(messageBytes, 0, messageBytes.Length);
            cryptoStream.FlushFinalBlock();

            
            byte[] encryptedMessageBytes = new byte[memStream.Length];
            memStream.Position = 0;
            memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);

            return encryptedMessageBytes;
        }

        
        
        static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {
            byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

            
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);
            CryptoStreamMode mode = CryptoStreamMode.Write;

            
            MemoryStream memStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
            cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
            cryptoStream.FlushFinalBlock();

            
            byte[] decryptedMessageBytes = new byte[memStream.Length];
            memStream.Position = 0;
            memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);

            return decryptedMessageBytes;
        }

        static void Main(string[] args) {
            byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };
            byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };

            byte[] encStr = Encrypt(plainBytes, keyBytes);
            Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr));

            byte[] decBytes = Decrypt(encStr, keyBytes);
            Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes));
        }
    }
}
Task: Native shebang




Go: 
package main

import (
    "fmt"
    "os"
)

func main() {
    if len(os.Args) > 1 {
        fmt.Println(os.Args[1])
    }
}
Task: Keyboard macros




Go: package main


import "C"
import "fmt"
import "unsafe"

func main() {
    d := C.XOpenDisplay(nil)
    f7, f6 := C.CString("F7"), C.CString("F6")
    defer C.free(unsafe.Pointer(f7))
    defer C.free(unsafe.Pointer(f6))

    if d != nil {
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
            C.Mod1Mask, 
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
            C.Mod1Mask,
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)

        var event C.XEvent
        for {
            C.XNextEvent(d, &event)
            if C.getXEvent_type(event) == C.KeyPress {
                xkeyEvent := C.getXEvent_xkey(event)
                s := C.XLookupKeysym(&xkeyEvent, 0)
                if s == C.XK_F7 {
                    fmt.Println("something's happened")
                } else if s == C.XK_F6 {
                    break
                }
            }
        }

        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
    } else {
        fmt.Println("XOpenDisplay did not succeed")
    }
}
Task: Tau function




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: Möbius function




Go: package main

import "fmt"

func möbius(to int) []int {
    if to < 1 {
        to = 1
    }
    mobs := make([]int, to+1) 
    primes := []int{2}
    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 {
                mobs[i] = 1
            } else {
                mobs[i] = -1
            }
        }
    }
    return mobs
}

func main() {
    mobs := möbius(199)
    fmt.Println("Möbius 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", mobs[i])
    }
}
Task: Execute Brain____




Go: package main

import "fmt"

func main() {
    
    
    bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}

func bf(dLen int, is string) {
    ds := make([]byte, dLen) 
    var dp int               
    for ip := 0; ip < len(is); ip++ {
        switch is[ip] {
        case '>':
            dp++
        case '<':
            dp--
        case '+':
            ds[dp]++
        case '-':
            ds[dp]--
        case '.':
            fmt.Printf("%c", ds[dp])
        case ',':
            fmt.Scanf("%c", &ds[dp])
        case '[':
            if ds[dp] == 0 {
                for nc := 1; nc > 0; {
                    ip++
                    if is[ip] == '[' {
                        nc++
                    } else if is[ip] == ']' {
                        nc--
                    }
                }
            }
        case ']':
            if ds[dp] != 0 {
                for nc := 1; nc > 0; {
                    ip--
                    if is[ip] == ']' {
                        nc++
                    } else if is[ip] == '[' {
                        nc--
                    }
                }
            }
        }
    }
}
Task: Coprime triplets




Go: package main

import (
    "fmt"
    "rcu"
)

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

func main() {
    const limit = 50
    cpt := []int{1, 2}
    for {
        m := 1
        l := len(cpt)
        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {
            m++
        }
        if m >= limit {
            break
        }
        cpt = append(cpt, m)
    }
    fmt.Printf("Coprime triplets under %d:\n", limit)
    for i, t := range cpt {
        fmt.Printf("%2d ", t)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\nFound %d such numbers\n", len(cpt))
}