WeixiangYan/CodeTransOcean huggingface dataset:
Task: Mersenne primes



C#: using System;
using System.Numerics;

namespace MersennePrimes {
    class Program {
        static BigInteger Sqrt(BigInteger x) {
            if (x < 0) throw new ArgumentException("Negative argument.");
            if (x < 2) return x;
            BigInteger y = x / 2;
            while (y > x / y) {
                y = ((x / y) + y) / 2;
            }
            return y;
        }

        static bool IsPrime(BigInteger bi) {
            if (bi < 2) return false;
            if (bi % 2 == 0) return bi == 2;
            if (bi % 3 == 0) return bi == 3;
            if (bi % 5 == 0) return bi == 5;
            if (bi % 7 == 0) return bi == 7;
            if (bi % 11 == 0) return bi == 11;
            if (bi % 13 == 0) return bi == 13;
            if (bi % 17 == 0) return bi == 17;
            if (bi % 19 == 0) return bi == 19;

            BigInteger limit = Sqrt(bi);
            BigInteger test = 23;
            while (test < limit) {
                if (bi % test == 0) return false;
                test += 2;
                if (bi % test == 0) return false;
                test += 4;
            }

            return true;
        }

        static void Main(string[] args) {
            const int MAX = 9;

            int pow = 2;
            int count = 0;

            while (true) {
                if (IsPrime(pow)) {
                    BigInteger p = BigInteger.Pow(2, pow) - 1;
                    if (IsPrime(p)) {
                        Console.WriteLine("2 ^ {0} - 1", pow);
                        if (++count >= MAX) {
                            break;
                        }
                    }
                }
                pow++;
            }
        }
    }
}
Task: Left factorials



C#: using System;
using System.Numerics;

namespace LeftFactorial
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i)));
            }

            for (int j = 20; j <= 110; j += 10)
            {
                Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j)));
            }

            for (int k = 1000; k <= 10000; k += 1000)
            {
                Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length));
            }

            Console.ReadKey();
        }

        private static BigInteger Factorial(int number)
        {
            BigInteger accumulator = 1;

            for (int factor = 1; factor <= number; factor++)
            {
                accumulator *= factor;
            }

            return accumulator;
        }

        private static BigInteger LeftFactorial(int n)
        {
            BigInteger result = 0;

            for (int i = 0; i < n; i++)
            {
                result += Factorial(i);
            }

            return result;
        }
    }
}
Task: Strange unique prime triplets



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

class Program { static void Main(string[] args) { string s;
  foreach (int lmt in new int[]{ 90, 300, 3000, 30000, 111000 }) {
    var pr = PG.Primes(lmt).Skip(1).ToList(); DT st = DT.Now;
    int d, f = 0; var r = new List<string>();
    int i = -1, m, h = (m = lmt / 3), j, k, pra, prab;
    while (i < 0) i = pr.IndexOf(h--); k = (j = i - 1) - 1;
    for (int a = 0; a <= k; a++) { pra = pr[a];
    for (int b = a + 1; b <= j; b++) { prab = pra + pr[b]; 
    for (int c = b + 1; c <= i; c++) {
      if (PG.flags[d = prab + pr[c]]) continue; f++;
      if (lmt < 100) r.Add(string.Format("{3,5} = {0,2} + {1,2} + {2,2}", pra, pr[b], pr[c], d)); } } }
    s = "s.u.p.t.s under "; r.Sort(); if (r.Count > 0) WriteLine("{0}{1}:\n{2}", s, m, string.Join("\n", r));
    if (lmt > 100) WriteLine("Count of {0}{1,6:n0}: {2,13:n0}  {3} sec", s, m, f, (DT.Now - st).ToString().Substring(6)); } } }

class PG { public static bool[] flags;
  public static IEnumerable<int> Primes(int lim) {
  flags = new bool[lim + 1]; int j = 2;
  for (int d = 3, sq = 4; sq <= lim; j++, sq += d += 2)
    if (!flags[j]) { yield return j;
      for (int k = sq; k <= lim; k += j) flags[k] = true; }
  for (; j <= lim; j++) if (!flags[j]) yield return j; } }
Task: Motzkin numbers



C#: using System;
using BI = System.Numerics.BigInteger;
 
class Program {
 
  
  static bool hmf(BI x) {
    if (x < 4) return x == 1;
    if ((x & 1) == 0 || x % 3 == 0) return true;
    int l = (int)Math.Sqrt((double)x); 
    for (int j = 5, d = 4; j <= l; j += d = 6 - d)
      if (x % j == 0) return x > j;
    return false;
  }
 
  static void Main(string[] args) {
    BI a = 0, b = 1, t;
    int n = 1, s = 0, d = 1, c = 0, f = 1;
    while (n <= 80)
      Console.WriteLine("{0,46:n0} {1}",
        t = b / n++,
        hmf(t) ? "" : "is prime.",
        t = b,
        b = ((c += d * 3 + 3) * a +
             (f += d * 2 + 3) * b) /
             (s += d += 2),
        a = t);
  }
}
Task: Self numbers



C#: using System;
using static System.Console;

class Program {

  const int mc = 103 * 1000 * 10000 + 11 * 9 + 1;

  static bool[] sv = new bool[mc + 1];

  static void sieve() { int[] dS = new int[10000];
    for (int a = 9, i = 9999; a >= 0; a--)
      for (int b = 9; b >= 0; b--)
        for (int c = 9, s = a + b; c >= 0; c--)
          for (int d = 9, t = s + c; d >= 0; d--)
            dS[i--] = t + d;
    for (int a = 0, n = 0; a < 103; a++)
      for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000)
        for (int c = 0, s = d + dS[b] + n; c < 10000; c++)
          sv[dS[c] + s++] = true; }

  static void Main() { DateTime st = DateTime.Now; sieve();
    WriteLine("Sieving took {0}s", (DateTime.Now - st).TotalSeconds); 
    WriteLine("\nThe first 50 self numbers are:");
    for (int i = 0, count = 0; count <= 50; i++) if (!sv[i]) {
        count++; if (count <= 50) Write("{0} ", i);
        else WriteLine("\n\n       Index     Self number"); }
    for (int i = 0, limit = 1, count = 0; i < mc; i++)
      if (!sv[i]) if (++count == limit) {
          WriteLine("{0,12:n0}   {1,13:n0}", count, i);
          if (limit == 1e9) break; limit *= 10; }
    WriteLine("\nOverall took {0}s", (DateTime.Now - st). TotalSeconds);
  }
}
Task: Minimum primes



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

class Program {

  static int nxtPrime(int x) {
    int j = 2; do {
        if (x % j == 0) { j = 2; x++; }
        else j += j < 3 ? 1 : 2;
    } while (j * j <= x); return x; }

  static void Main(string[] args) {
    WriteLine("working...");
    int[] Num1 = new int[]{  5, 45, 23, 21, 67 },
          Num2 = new int[]{ 43, 22, 78, 46, 38 },
          Num3 = new int[]{  9, 98, 12, 54, 53 };
    int n = Num1.Length; int[] Nums = new int[n];
    for (int i = 0; i < n; i++)
      Nums[i] = nxtPrime(new int[]{ Num1[i], Num2[i], Num3[i] }.Max());
    WriteLine("The minimum prime numbers of three lists = [{0}]", string.Join(",", Nums));
    Write("done..."); } }
Task: Type detection



C#: using System;

namespace TypeDetection {
    class C { }
    struct S { }
    enum E {
        NONE,
    }

    class Program {
        static void ShowType<T>(T t) {
            Console.WriteLine("The type of '{0}' is {1}", t, t.GetType());
        }

        static void Main() {
            ShowType(5);
            ShowType(7.5);
            ShowType('d');
            ShowType(true);
            ShowType("Rosetta");
            ShowType(new C());
            ShowType(new S());
            ShowType(E.NONE);
            ShowType(new int[] { 1, 2, 3 });
        }
    }
}
Task: Primes which contain only one odd digit



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

class Program
{
    
    
    static List<uint> sieve(uint max, bool ordinary = false)
    {
        uint k = ((max - 3) >> 1) + 1,
           lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;
        var pl = new List<uint> { };
        var ic = new bool[k];
        for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])
                for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;
        if (ordinary)
        {
            pl.Add(2);
            for (uint i = 0, j = 3; i < k; i++, j += 2)
                if (!ic[i]) pl.Add(j);
        }
        else
            for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)
                if (!ic[i])
                {
                    while ((t /= 10) > 0)
                        if (((t % 10) & 1) == 1) goto skip;
                    pl.Add(j);
                skip:;
                }
        return pl;
    }

    static void Main(string[] args)
    {
        var pl = sieve((uint)1e9);
        uint c = 0, l = 10, p = 1;
        Console.WriteLine("List of one-odd-digit primes < 1,000:");
        for (int i = 0; pl[i] < 1000; i++)
            Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : "  ");
        string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})";
        foreach (var itm in pl)
            if (itm < l) c++;
            else Console.Write(fmt, c++, p++, l, l *= 10);
        Console.Write(fmt, c++, p++, l);
    }
}
Task: Safe primes and unsafe primes



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

public static class SafePrimes
{
    public static void Main() {
        HashSet<int> primes = Primes(10_000_000).ToHashSet();
        WriteLine("First 35 safe primes:");
        WriteLine(string.Join(" ", primes.Where(IsSafe).Take(35)));
        WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsSafe):n0} safe primes below {1_000_000:n0}");
        WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsSafe):n0} safe primes below {10_000_000:n0}");
        WriteLine("First 40 unsafe primes:");
        WriteLine(string.Join(" ", primes.Where(IsUnsafe).Take(40)));
        WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsUnsafe):n0} unsafe primes below {1_000_000:n0}");
        WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsUnsafe):n0} unsafe primes below {10_000_000:n0}");

        bool IsSafe(int prime) => primes.Contains(prime / 2);
        bool IsUnsafe(int prime) => !primes.Contains(prime / 2);
    }

    
    static IEnumerable<int> Primes(int bound) {
        if (bound < 2) yield break;
        yield return 2;

        BitArray composite = new BitArray((bound - 1) / 2);
        int limit = ((int)(Math.Sqrt(bound)) - 1) / 2;
        for (int i = 0; i < limit; i++) {
            if (composite[i]) continue;
            int prime = 2 * i + 3;
            yield return prime;
            for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true;
        }
        for (int i = limit; i < composite.Count; i++) {
            if (!composite[i]) yield return 2 * i + 3;
        }
    }

}
Task: Hash join



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

namespace HashJoin
{
    public class AgeName
    {
        public AgeName(byte age, string name)
        {
            Age = age;
            Name = name;
        }
        public byte Age { get; private set; }
        public string Name { get; private set; }
    }

    public class NameNemesis
    {
        public NameNemesis(string name, string nemesis)
        {
            Name = name;
            Nemesis = nemesis;
        }
        public string Name { get; private set; }
        public string Nemesis { get; private set; }
    }

    public class DataContext
    {
        public DataContext()
        {
            AgeName = new List<AgeName>();
            NameNemesis = new List<NameNemesis>();
        }
        public List<AgeName> AgeName { get; set; }
        public List<NameNemesis> NameNemesis { get; set; }
    }

    public class AgeNameNemesis
    {
        public AgeNameNemesis(byte age, string name, string nemesis)
        {
            Age = age;
            Name = name;
            Nemesis = nemesis;
        }
        public byte Age { get; private set; }
        public string Name { get; private set; }
        public string Nemesis { get; private set; }
    }

    class Program
    {
        public static void Main()
        {
            var data = GetData();
            var result = ExecuteHashJoin(data);
            WriteResultToConsole(result);
        }

        private static void WriteResultToConsole(List<AgeNameNemesis> result)
        {
            result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}",
                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));
        }

        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)
        {
            return (data.AgeName.Join(data.NameNemesis, 
                ageName => ageName.Name, nameNemesis => nameNemesis.Name,
                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))
                .ToList();
        }

        private static DataContext GetData()
        {
            var context = new DataContext();

            context.AgeName.AddRange(new [] {
                    new AgeName(27, "Jonah"), 
                    new AgeName(18, "Alan"), 
                    new AgeName(28, "Glory"), 
                    new AgeName(18, "Popeye"), 
                    new AgeName(28, "Alan")
                });

            context.NameNemesis.AddRange(new[]
            {
                new NameNemesis("Jonah", "Whales"),
                new NameNemesis("Jonah", "Spiders"),
                new NameNemesis("Alan", "Ghosts"),
                new NameNemesis("Alan", "Zombies"),
                new NameNemesis("Glory", "Buffy")
            });

            return context;
        }
    }
}
Task: Largest palindrome product



C#: using System;
class Program {

  static bool isPal(int n) {
    int rev = 0, lr = -1, rem;
    while (n > rev) {
      n = Math.DivRem(n, 10, out rem);
      if (lr < 0 && rem == 0) return false;
      lr = rev; rev = 10 * rev + rem;
      if (n == rev || n == lr) return true;
    } return false; }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;
    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = "";
    y /= 11;
    if ((y & 1) == 0) y--;
    if (y % 5 == 0) y -= 2;
    y *= 11;
    while (y <= max) {
      c = 0;
      y10 = y * 10;
      z = max9 + a[ld = y % 10];
      p = y * z;
      while (p >= bp) {
        if (isPal(p)) {
          if (p > bp) bp = p;
          bs = string.Format("{0} x {1} = {2}", y, z - c, bp);
        }
        p -= y10; c += 10;
      }
      y += ld == 3 ? 44 : 22;
    }
    sw.Stop();
    Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0);
  }
}
Task: Find largest left truncatable prime in a given base



C#: using Mpir.NET;  
using System;   
using System.Collections.Generic;
class MaxLftTrP_B   
{
    static void Main()
    {
        mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3);
        for (uint b = 3; b < 13; b++)
        {
            sw.Restart(); p = L(b);
            Console.WriteLine("{0} {1,2} {2}", sw.Elapsed, b, p);
        }
        Console.Read();
    }

    static mpz_t L(uint b)
    {
        var p = new List<mpz_t>(); mpz_t np = 0;
        while ((np = nxtP(np)) < b) p.Add(np);
        int i0 = 0, i = 0, i1 = p.Count - 1; mpz_t n0 = b, n, n1 = b * (b - 1);
        for (; i < p.Count; n0 *= b, n1 *= b, i0 = i1 + 1, i1 = p.Count - 1)
            for (n = n0; n <= n1; n += n0)
                for (i = i0; i <= i1; i++)
                    if (mpir.mpz_probab_prime_p(np = n + p[i], 15) > 0) p.Add(np);
        return p[p.Count - 1];
    }

    static mpz_t nxtP(mpz_t n) { mpz_t p = 0; mpir.mpz_nextprime(p, n); return p; }
}
Task: Set of real numbers



C#: using System;

namespace RosettaCode.SetOfRealNumbers
{
    public class Set<TValue>
    {
        public Set(Predicate<TValue> contains)
        {
            Contains = contains;
        }

        public Predicate<TValue> Contains
        {
            get;
            private set;
        }

        public Set<TValue> Union(Set<TValue> set)
        {
            return new Set<TValue>(value => Contains(value) || set.Contains(value));
        }

        public Set<TValue> Intersection(Set<TValue> set)
        {
            return new Set<TValue>(value => Contains(value) && set.Contains(value));
        }

        public Set<TValue> Difference(Set<TValue> set)
        {
            return new Set<TValue>(value => Contains(value) && !set.Contains(value));
        }
    }
}
Task: Monads_Maybe monad



C#: using System;

namespace RosettaMaybe
{
    
    public abstract class Maybe<T>
    {
        public sealed class Some : Maybe<T>
        {
            public Some(T value) => Value = value;
            public T Value { get; }
        }
        public sealed class None : Maybe<T> { }
    }

    class Program
    {
        static Maybe<double> MonadicSquareRoot(double x)
        {
            if (x >= 0)
            {
                return new Maybe<double>.Some(Math.Sqrt(x));
            }
            else
            {
                return new Maybe<double>.None();
            }
        }
        static void Main(string[] args)
        {
            foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 })
            {
                Maybe<double> maybe = MonadicSquareRoot(x);
                if (maybe is Maybe<double>.Some some)
                {
                    Console.WriteLine($"The square root of {x} is " + some.Value);
                }
                else
                {
                    Console.WriteLine($"Square root of {x} is undefined.");
                }
            }
        }
    }
}
Task: Church numerals



C#: using System;
 
public delegate Church Church(Church f);
 
public static class ChurchNumeral
{
    public static readonly Church ChurchZero = _ => x => x;
    public static readonly Church ChurchOne = f => f;
 
    public static Church Successor(this Church n) => f => x => f(n(f)(x));
    public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
    public static Church Multiply(this Church m, Church n) => f => m(n(f));
    public static Church Exponent(this Church m, Church n) => n(m);
    public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
    public static Church Predecessor(this Church n) =>
      f => x => n(g => h => h(g(f)))(_ => x)(a => a);
    public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
    static Church looper(this Church v, Church d) =>
        v(_ => v.divr(d).Successor())(ChurchZero);
    static Church divr(this Church n, Church d) =>
        n.Subtract(d).looper(d);
    public static Church Divide(this Church dvdnd, Church dvsr) =>
        (dvdnd.Successor()).divr(dvsr);
 
    public static Church FromInt(int i) =>
      i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
 
    public static int ToInt(this Church ch) {
        int count = 0;
        ch(x => { count++; return x; })(null);
        return count;
    }
 
    public static void Main() {
        Church c3 = FromInt(3);
        Church c4 = c3.Successor();
        Church c11 = FromInt(11);
        Church c12 = c11.Successor();
        int sum = c3.Add(c4).ToInt();
        int product = c3.Multiply(c4).ToInt();
        int exp43 = c4.Exponent(c3).ToInt();
        int exp34 = c3.Exponent(c4).ToInt();
        int tst0 = ChurchZero.IsZero().ToInt();
        int pred4 = c4.Predecessor().ToInt();
        int sub43 = c4.Subtract(c3).ToInt();
        int div11by3 = c11.Divide(c3).ToInt();
        int div12by3 = c12.Divide(c3).ToInt();
        Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
        Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
    } 
}
Task: Long primes



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

public static class LongPrimes
{
    public static void Main() {
        var primes = SomePrimeGenerator.Primes(64000).Skip(1).Where(p => Period(p) == p - 1).Append(99999);
        Console.WriteLine(string.Join(" ", primes.TakeWhile(p => p <= 500)));
        int count = 0, limit = 500;
        foreach (int prime in primes) {
            if (prime > limit) {
                Console.WriteLine($"There are {count} long primes below {limit}");
                limit *= 2;
            }
            count++;
        }

        int Period(int n) {
            int r = 1, rr;
            for (int i = 0; i <= n; i++) r = 10 * r % n;
            rr = r;
            for (int period = 1;; period++) {
                r = (10 * r) % n;
                if (r == rr) return period;
            }
        }
    }

}

static class SomePrimeGenerator {

    public static IEnumerable<int> Primes(int lim) {
        bool [] flags = new bool[lim + 1]; int j = 2;
        for (int d = 3, sq = 4; sq <= lim; j++, sq += d += 2)
            if (!flags[j]) {
                yield return j; for (int k = sq; k <= lim; k += j)
                    flags[k] = true;
            }
        for (; j<= lim; j++) if (!flags[j]) yield return j;
    }
}
Task: Cuban primes



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

static class Program
{
    static List<long> primes = new List<long>() { 3, 5 };

     static void Main(string[] args)
    {
        const int cutOff = 200;
        const int bigUn = 100000;
        const int chunks = 50;
        const int little = bigUn / chunks;
        const string tn = " cuban prime";
        Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn);
        int c = 0;
        bool showEach = true;
        long u = 0, v = 1;
        DateTime st = DateTime.Now;
        for (long i = 1; i <= long.MaxValue; i++)
        {
            bool found = false;
            int mx = System.Convert.ToInt32(Math.Ceiling(Math.Sqrt(v += (u += 6))));
            foreach (long item in primes)
            {
                if (item > mx) break;
                if (v % item == 0) { found = true; break; }
            }
            if (!found)
            {
                c += 1; if (showEach)
                {
                    for (var z = primes.Last() + 2; z <= v - 2; z += 2)
                    {
                        bool fnd = false;
                        foreach (long item in primes)
                        {
                            if (item > mx) break;
                            if (z % item == 0) { fnd = true; break; }
                        }
                        if (!fnd) primes.Add(z);
                    }
                    primes.Add(v); Console.Write("{0,11:n0}", v);
                    if (c % 10 == 0) Console.WriteLine();
                    if (c == cutOff)
                    {
                        showEach = false;
                        Console.Write("\nProgress to the {0:n0}th{1}: ", bigUn, tn);
                    }
                }
                if (c % little == 0) { Console.Write("."); if (c == bigUn) break; }
            }
        }
        Console.WriteLine("\nThe {1:n0}th{2} is {0,17:n0}", v, c, tn);
        Console.WriteLine("Computation time was {0} seconds", (DateTime.Now - st).TotalSeconds);
        if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
    }
}