WeixiangYan/CodeTransOcean huggingface dataset:
Task: Cuban primes

C: #include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef long long llong_t;
struct PrimeArray {
    llong_t *ptr;
    size_t size;
    size_t capacity;
};

struct PrimeArray allocate() {
    struct PrimeArray primes;

    primes.size = 0;
    primes.capacity = 10;
    primes.ptr = malloc(primes.capacity * sizeof(llong_t));

    return primes;
}

void deallocate(struct PrimeArray *primes) {
    free(primes->ptr);
    primes->ptr = NULL;
}

void push_back(struct PrimeArray *primes, llong_t p) {
    if (primes->size >= primes->capacity) {
        size_t new_capacity = (3 * primes->capacity) / 2 + 1;
        llong_t *temp = realloc(primes->ptr, new_capacity * sizeof(llong_t));
        if (NULL == temp) {
            fprintf(stderr, "Failed to reallocate the prime array.");
            exit(1);
        } else {
            primes->ptr = temp;
            primes->capacity = new_capacity;
        }
    }

    primes->ptr[primes->size++] = p;
}

int main() {
    const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks;
    struct PrimeArray primes = allocate();
    int c = 0;
    bool showEach = true;
    llong_t u = 0, v = 1, i;

    push_back(&primes, 3);
    push_back(&primes, 5);

    printf("The first %d cuban primes:\n", cutOff);
    for (i = 1; i < LLONG_MAX; ++i) {
        bool found = false;
        llong_t mx = ceil(sqrt(v += (u += 6)));
        llong_t j;

        for (j = 0; j < primes.size; ++j) {
            if (primes.ptr[j] > mx) {
                break;
            }
            if (v % primes.ptr[j] == 0) {
                found = true;
                break;
            }
        }
        if (!found) {
            c += 1;
            if (showEach) {
                llong_t z;
                for (z = primes.ptr[primes.size - 1] + 2; z <= v - 2; z += 2) {
                    bool fnd = false;

                    for (j = 0; j < primes.size; ++j) {
                        if (primes.ptr[j] > mx) {
                            break;
                        }
                        if (z % primes.ptr[j] == 0) {
                            fnd = true;
                            break;
                        }
                    }
                    if (!fnd) {
                        push_back(&primes, z);
                    }
                }
                push_back(&primes, v);
                printf("%11lld", v);
                if (c % 10 == 0) {
                    printf("\n");
                }
                if (c == cutOff) {
                    showEach = false;
                    printf("\nProgress to the %dth cuban prime: ", bigUn);
                }
            }
            if (c % little == 0) {
                printf(".");
                if (c == bigUn) {
                    break;
                }
            }
        }
    }
    printf("\nThe %dth cuban prime is %lld\n", c, v);

    deallocate(&primes);
    return 0;
}
Task: Chaos game

C: #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){
	
	time_t t;
	double side, vertices[3][3],seedX,seedY,windowSide;
	int i,iter,choice;
	
	printf("Enter triangle side length : ");
	scanf("%lf",&side);
	
	printf("Enter number of iterations : ");
	scanf("%d",&iter);
	
	windowSide = 10 + 2*side;

	initwindow(windowSide,windowSide,"Sierpinski Chaos");
	
	for(i=0;i<3;i++){
		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);
		putpixel(vertices[i][0],vertices[i][1],15);
	}
	
	srand((unsigned)time(&t));
	
	seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);
	seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);
	
	putpixel(seedX,seedY,15);
	
	for(i=0;i<iter;i++){
		choice = rand()%3;
		
		seedX = (seedX + vertices[choice][0])/2;
		seedY = (seedY + vertices[choice][1])/2;
		
		putpixel(seedX,seedY,15);
	}
	
	getch();
	
	closegraph();
	
	return 0;
}
Task: World Cup group stage

C: #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int compare(const void *a, const void *b) {
    int int_a = *((int *)a);
    int int_b = *((int *)b);
    return (int_a > int_b) - (int_a < int_b);
}

char results[7];
bool next_result() {
    char *ptr = results + 5;
    int num = 0;
    size_t i;

    
    if (strcmp(results, "222222") == 0) {
        return false;
    }

    
    for (i = 0; results[i] != 0; i++) {
        int d = results[i] - '0';
        num = 3 * num + d;
    }

    
    num++;

    
    while (num > 0) {
        int rem = num % 3;
        num /= 3;
        *ptr-- = rem + '0';
    }
    
    while (ptr > results) {
        *ptr-- = '0';
    }

    return true;
}

char *games[6] = { "12", "13", "14", "23", "24", "34" };
char *places[4] = { "1st", "2nd", "3rd", "4th" };
int main() {
    int points[4][10];
    size_t i, j;

    strcpy(results, "000000");
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 10; j++) {
            points[i][j] = 0;
        }
    }

    do {
        int records[] = { 0, 0, 0, 0 };

        for (i = 0; i < 6; i++) {
            switch (results[i]) {
            case '2':
                records[games[i][0] - '1'] += 3;
                break;
            case '1':
                records[games[i][0] - '1']++;
                records[games[i][1] - '1']++;
                break;
            case '0':
                records[games[i][1] - '1'] += 3;
                break;
            default:
                break;
            }
        }

        qsort(records, 4, sizeof(int), compare);
        for (i = 0; i < 4; i++) {
            points[i][records[i]]++;
        }
    } while (next_result());

    printf("POINTS       0    1    2    3    4    5    6    7    8    9\n");
    printf("-----------------------------------------------------------\n");
    for (i = 0; i < 4; i++) {
        printf("%s place", places[i]);
        for (j = 0; j < 10; j++) {
            printf("%5d", points[3 - i][j]);
        }
        printf("\n");
    }

    return 0;
}
Task: Perlin noise

C: #include<stdlib.h>
#include<stdio.h>
#include<math.h>

int p[512];

double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
      int h = hash & 15;                      
      double u = h<8 ? x : y,                 
             v = h<4 ? y : h==12||h==14 ? x : z;
      return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
   }
   
double noise(double x, double y, double z) {
      int X = (int)floor(x) & 255,                  
          Y = (int)floor(y) & 255,                  
          Z = (int)floor(z) & 255;
      x -= floor(x);                                
      y -= floor(y);                                
      z -= floor(z);
      double u = fade(x),                                
             v = fade(y),                                
             w = fade(z);
      int A = p[X  ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,      
          B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;   
 
      return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ), 
                                     grad(p[BA  ], x-1, y  , z   )),
                             lerp(u, grad(p[AB  ], x  , y-1, z   ), 
                                     grad(p[BB  ], x-1, y-1, z   ))),
                     lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ), 
                                     grad(p[BA+1], x-1, y  , z-1 )), 
                             lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
                                     grad(p[BB+1], x-1, y-1, z-1 ))));
   }

void loadPermutation(char* fileName){
	FILE* fp = fopen(fileName,"r");
	int permutation[256],i;
	
	for(i=0;i<256;i++)
		fscanf(fp,"%d",&permutation[i]);
	
	fclose(fp);
	
	for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}

int main(int argC,char* argV[])
{
	if(argC!=5)
		printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>");
	else{
		loadPermutation(argV[1]);
		printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
	}
	
	return 0;
}
Task: OpenGL_Utah teapot

C: #include<gl/freeglut.h>

double rot = 0;
float matCol[] = {1,0,0,0};

void display(){
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glPushMatrix();
	glRotatef(30,1,1,0);
	glRotatef(rot,0,1,1);
	glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);
	glutWireTeapot(0.5);
	glPopMatrix();
	glFlush();
}


void onIdle(){
	rot += 0.01;
	glutPostRedisplay();
}

void init(){
	float pos[] = {1,1,1,0};
	float white[] = {1,1,1,0};
	float shini[] = {70};
	
	glClearColor(.5,.5,.5,0);
	glShadeModel(GL_SMOOTH);
	glLightfv(GL_LIGHT0,GL_AMBIENT,white);
	glLightfv(GL_LIGHT0,GL_DIFFUSE,white);
	glMaterialfv(GL_FRONT,GL_SHININESS,shini);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_DEPTH_TEST);
}

int main(int argC, char* argV[])
{
	glutInit(&argC,argV);
	glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
	glutInitWindowSize(900,700);
	glutCreateWindow("The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.");
	init();
	glutDisplayFunc(display);
	glutIdleFunc(onIdle);
	glutMainLoop();
	return 0;
}
Task: Sine wave

C: #include <stdio.h>
#include <math.h>
#include <stdlib.h>


int header[] = {46, 115, 110, 100, 0, 0, 0, 24,
                255, 255, 255, 255, 0, 0, 0, 3,
                0, 0, 172, 68, 0, 0, 0, 1};

int main(int argc, char *argv[]){
        float freq, dur;
        long i, v;

        if (argc < 3) {
                printf("Usage:\n");
                printf("  csine <frequency> <duration>\n");
                exit(1);
        }
        freq = atof(argv[1]);
        dur = atof(argv[2]);
        for (i = 0; i < 24; i++)
                putchar(header[i]);
        for (i = 0; i < dur * 44100; i++) {
                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));
                v = v % 65536;
                putchar(v >> 8);
                putchar(v % 256);
        }
}
Task: Square root by hand



C#: using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;

class Program {

    static void Main(string[] args) {
        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
        DateTime st = DateTime.Now;
        if (args.Length > 0) int.TryParse(args[0], out n);
        if (n > 0) n0 = n; else n = 1;
        do {
            Write(d); i = (i - k * d) * 100; k = 20 * j;
            for (d = 1; d <= 10; d++)
                if ((k + d) * d > i) { d -= 1; break; }
            j = j * 10 + d; k += d; if (n0 > 0) n--;
        } while (n > 0);
        if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }

}
Task: Primes with digits in nondecreasing order



C#: using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
 
class Program {

  static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  
  static string from10(int b) { string res = ""; int re; while (b > 0) {
    b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }

  
  static int to10(string s) { int res = 0; foreach (char i in s)
    res = res * ba + chars.IndexOf(i); return res; }

  
  static bool nd(string s) { if (s.Length < 2) return true;
    char l = s[0]; for (int i = 1; i < s.Length; i++)
      if (chars.IndexOf(l) > chars.IndexOf(s[i]))
        return false; else l = s[i] ; return true; }

  static void Main(string[] args) { int c, lim = 1000; string s;
    foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
      ba = b; c = 0; foreach (var a in PG.Primes(lim))
        if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
    WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } 
 
class PG { public static IEnumerable<int> Primes(int lim) {
    var flags = new bool[lim + 1]; int j; yield return 2;
    for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
      if (!flags[j]) { yield return 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 j; } }
Task: Smallest square that begins with n



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        int i, d, s, t, n = 50, c = 1;
        var sw = new int[n];
        for (i = d = s = 1; c < n; i++, s += d += 2)
            for (t = s; t > 0; t /= 10)
                if (t < n && sw[t] < 1)
                    Console.Write("", sw[t] = s, c++);
        Console.Write(string.Join(" ", sw).Substring(2));
    }
}
Task: Intersecting number wheels



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

public static class IntersectingNumberWheels
{
    public static void Main() {
        TurnWheels(('A', "123")).Take(20).Print();
        TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print();
        TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Print();
        TurnWheels(('A', "1BC"), ('B', "34"), ('C', "5B")).Take(20).Print();
    }

    static IEnumerable<char> TurnWheels(params (char name, string values)[] wheels) {
        var data = wheels.ToDictionary(wheel => wheel.name, wheel => wheel.values.Loop().GetEnumerator());
        var primary = data[wheels[0].name];
        while (true) {
            yield return Turn(primary);
        }

        char Turn(IEnumerator<char> sequence) {
            sequence.MoveNext();
            char c = sequence.Current;
            return char.IsDigit(c) ? c : Turn(data[c]);
        }
    }

    static IEnumerable<T> Loop<T>(this IEnumerable<T> seq) {
        while (true) {
            foreach (T element in seq) yield return element;
        }
    }

    static void Print(this IEnumerable<char> sequence) => Console.WriteLine(string.Join(" ", sequence));
}
Task: Color of a screen pixel



C#: using System;
using System.Drawing;
using System.Windows.Forms;

class Program
{
    static Color GetPixel(Point position)
    {
        using (var bitmap = new Bitmap(1, 1))
        {
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1));
            }
            return bitmap.GetPixel(0, 0);
        }
    }

    static void Main()
    {
        Console.WriteLine(GetPixel(Cursor.Position));
    }
}
Task: Circles of given radius through two points



C#: using System;
public class CirclesOfGivenRadiusThroughTwoPoints
{
    public static void Main()
    {
        double[][] values = new double[][] {
            new [] { 0.1234, 0.9876, 0.8765, 0.2345,   2 },
            new [] { 0.0,       2.0,    0.0,    0.0,   1 },
            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   2 },
            new [] { 0.1234, 0.9876, 0.8765, 0.2345, 0.5 },
            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   0 }
        };
		
        foreach (var a in values) {
            var p = new Point(a[0], a[1]);
            var q = new Point(a[2], a[3]);
            Console.WriteLine($"Points {p} and {q} with radius {a[4]}:");
            try {
                var centers = FindCircles(p, q, a[4]);
                Console.WriteLine("\t" + string.Join(" and ", centers));
            } catch (Exception ex) {
                Console.WriteLine("\t" + ex.Message);
            }
        }
    }
	
    static Point[] FindCircles(Point p, Point q, double radius) {
        if(radius < 0) throw new ArgumentException("Negative radius.");
        if(radius == 0) {
            if(p == q) return new [] { p };
            else throw new InvalidOperationException("No circles.");
        }
        if (p == q) throw new InvalidOperationException("Infinite number of circles.");
		
        double sqDistance = Point.SquaredDistance(p, q);
        double sqDiameter = 4 * radius * radius;
        if (sqDistance > sqDiameter) throw new InvalidOperationException("Points are too far apart.");
		
        Point midPoint = new Point((p.X + q.X) / 2, (p.Y + q.Y) / 2);
        if (sqDistance == sqDiameter) return new [] { midPoint };
		
        double d = Math.Sqrt(radius * radius - sqDistance / 4);
        double distance = Math.Sqrt(sqDistance);
        double ox = d * (q.X - p.X) / distance, oy = d * (q.Y - p.Y) / distance;
        return new [] {
            new Point(midPoint.X - oy, midPoint.Y + ox),
            new Point(midPoint.X + oy, midPoint.Y - ox)
        };
    }
	
    public struct Point
    {
        public Point(double x, double y) : this() {
            X = x;
            Y = y;
        }
	
        public double X { get; }
        public double Y { get; }
	
        public static bool operator ==(Point p, Point q) => p.X == q.X && p.Y == q.Y;
        public static bool operator !=(Point p, Point q) => p.X != q.X || p.Y != q.Y;
	
        public static double SquaredDistance(Point p, Point q) {
            double dx = q.X - p.X, dy = q.Y - p.Y;
            return dx * dx + dy * dy;
        }
		
        public override string ToString() => $"({X}, {Y})";
		
    }	
}
Task: Merge and aggregate datasets



C#: using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;

public static class MergeAndAggregateDatasets
{
    public static void Main()
    {
        string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz";

        string visitsCsv = @"
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3";

        string format = "yyyy-MM-dd";
        var formatProvider = new DateTimeFormat(format).FormatProvider;

        var patients = ParseCsv(
            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
            line => (PatientId: int.Parse(line[0]), LastName: line[1]));

        var visits = ParseCsv(
            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
            line => (
                PatientId: int.Parse(line[0]),
                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),
                Score: double.TryParse(line[2], out double score) ? score : default(double?)
            )
        );

        var results =
            patients.GroupJoin(visits,
                p => p.PatientId,
                v => v.PatientId,
                (p, vs) => (
                    p.PatientId,
                    p.LastName,
                    LastVisit: vs.Max(v => v.VisitDate),
                    ScoreSum: vs.Sum(v => v.Score),
                    ScoreAvg: vs.Average(v => v.Score)
                )
            ).OrderBy(r => r.PatientId);

        Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |");
        foreach (var r in results) {
            Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |");
        }
    }

    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)
    {
        for (int i = 1; i < contents.Length; i++) {
            var line = contents[i].Split(',');
            yield return constructor(line);
        }
    }

}
Task: XML_XPath



C#: XmlReader XReader;
 

XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
 

XReader = XmlReader.Create("xmlfile.xml");
 


IXPathNavigable XDocument = new XPathDocument(XReader);
 

XPathNavigator Nav = XDocument.CreateNavigator();
Nav = Nav.SelectSingleNode("
 

if(Nav.MoveToFirst())
{
  Console.WriteLine(Nav.OuterXml); 
}
 

XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("
 
while (Iterator.MoveNext())
{
  Console.WriteLine(Iterator.Current.Value);
}
 
Iterator = XDocument.CreateNavigator().Select("
 

List<string> NodesValues = new List<string>();
 
while (Iterator.MoveNext())
{
  NodesValues.Add(Iterator.Current.Value);
}
 

Console.WriteLine(NodesValues.ToArray().Length);
Task: Straddling checkerboard



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

namespace StraddlingCheckerboard
{
    class Program
    {
        public readonly static IReadOnlyDictionary<char, string> val2Key;
        public readonly static IReadOnlyDictionary<string, char> key2Val;

        static Program()
        {
            val2Key = new Dictionary<char, string> {
                {'A',"30"},  {'B',"31"}, {'C',"32"},  {'D',"33"},  {'E',"5"},   {'F',"34"},  {'G',"35"},
                {'H',"0"},   {'I',"36"}, {'J',"37"},  {'K',"38"},  {'L',"2"},   {'M',"4"},   {'.',"78"},
                {'N',"39"},  {'/',"79"}, {'O',"1"},   {'0',"790"}, {'P',"70"},  {'1',"791"}, {'Q',"71"},
                {'2',"792"}, {'R',"8"},  {'3',"793"}, {'S',"6"},   {'4',"794"}, {'T',"9"},   {'5',"795"},
                {'U',"72"},  {'6',"796"},{'V',"73"},  {'7',"797"}, {'W',"74"},  {'8',"798"}, {'X',"75"},
                {'9',"799"}, {'Y',"76"}, {'Z',"77"}};

            key2Val = val2Key.ToDictionary(kv => kv.Value, kv => kv.Key);
        }

        public static string Encode(string s)
        {
            return string.Concat(s.ToUpper().ToCharArray()
                .Where(c => val2Key.ContainsKey(c)).Select(c => val2Key[c]));
        }

        public static string Decode(string s)
        {
            return string.Concat(Regex.Matches(s, "79.|7.|3.|.").Cast<Match>()
                .Where(m => key2Val.ContainsKey(m.Value)).Select(m => key2Val[m.Value]));
        }

        static void Main(string[] args)
        {
            var enc = Encode("One night-it was on the twentieth of March, 1888-I was returning");
            Console.WriteLine(enc);
            Console.WriteLine(Decode(enc));

            Console.ReadLine();
        }
    }
}
Task: Write to Windows event log



C#: using System.Diagnostics;

namespace RC
{
  internal class Program
  {
    public static void Main()
    {
      string sSource  = "Sample App";
      string sLog     = "Application";
      string sEvent   = "Hello from RC!";

      if (!EventLog.SourceExists(sSource))
        EventLog.CreateEventSource(sSource, sLog);

      EventLog.WriteEntry(sSource, sEvent);
      EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);
    }
  }
}
Task: Magnanimous numbers



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

class Program {

  static bool[] np; 

  static void ms(long lmt) { 
    np = new bool[lmt]; np[0] = np[1] = true;
    for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])
        for (long k = n * n; k < lmt; k += n) np[k] = true; }

  static bool is_Mag(long n) { long res, rem;
    for (long p = 10; n >= p; p *= 10) {
      res = Math.DivRem (n, p, out rem);
      if (np[res + rem]) return false; } return true; }

  static void Main(string[] args) { ms(100_009); string mn;
    WriteLine("First 45{0}", mn = " magnanimous numbers:");
    for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {
      if (c++ < 45 || (c > 240 && c <= 250) || c > 390)
        Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l);
      if (c < 45 && c % 15 == 0) WriteLine();
      if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn);
      if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } }
}