WeixiangYan/CodeTransOcean huggingface dataset:
Task: Largest difference between adjacent primes

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

int isprime( int p ) {
    int i;
    if(p==2) return 1;
    if(!(p%2)) return 0;
    for(i=3; i*i<=p; i+=2) {
       if(!(p%i)) return 0;
    }
    return 1;
}

int nextprime( int p ) {
    int i=0;
    if(p==0) return 2;
    if(p<3) return p+1;
    while(!isprime(++i + p));
    return i+p;
}

int main(void) {
    int i=3, j=5, champ=3, champj=5, record=2;
    for(i=3;j<=1000000;i=j) {
        j=nextprime(i);
        if(j-i>record) {
            champ=i;
            champj=j;
            record = j-i;
        }
    }
    printf( "The largest difference was %d, between %d and %d.\n", record, champ, champj );
    return 0;
}
Task: Minimum primes

C: #include <stdio.h>

#define TRUE 1
#define FALSE 0

int isPrime(int n) {
    int d;
    if (n < 2) return FALSE;
    if (n%2 == 0) return n == 2;
    if (n%3 == 0) return n == 3;
    d = 5;
    while (d*d <= n) {
        if (!(n%d)) return FALSE;
        d += 2;
        if (!(n%d)) return FALSE;
        d += 4;
    }
    return TRUE;
}

int max(int a, int b) {
    if (a > b) return a;
    return b;
}

int main() {
    int n, m;
    int numbers1[5] = { 5, 45, 23, 21, 67};
    int numbers2[5] = {43, 22, 78, 46, 38};
    int numbers3[5] = { 9, 98, 12, 54, 53};
    int primes[5]   = {};
    for (n = 0; n < 5; ++n) {
        m = max(max(numbers1[n], numbers2[n]), numbers3[n]);
        if (!(m % 2)) m++;
        while (!isPrime(m)) m += 2;
        primes[n] = m;
        printf("%d ", primes[n]);
    }
    printf("\n");
    return 0;
}
Task: Smallest power of 6 whose decimal expansion contains n

C: #include <stdio.h>
#include <string.h>
#include <gmp.h>

char *power_of_six(unsigned int n, char *buf) {
    mpz_t p;
    mpz_init(p);
    mpz_ui_pow_ui(p, 6, n);
    mpz_get_str(buf, 10, p);
    mpz_clear(p);
    return buf;
}

char *smallest_six(unsigned int n) {
    static char nbuf[32], powbuf[1024];
    unsigned int p = 0;
    
    do {
        sprintf(nbuf, "%u", n);
        power_of_six(p++, powbuf);
    } while (!strstr(powbuf, nbuf));
    
    return powbuf;
}

int main() {
    unsigned int i;
    
    for (i=0; i<22; i++) {
        printf("%d: %s\n", i, smallest_six(i));
    }
    
    return 0;
}
Task: Own digits power sum

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

#define MAX_DIGITS 9

int digits[MAX_DIGITS];

void getDigits(int i) {
    int ix = 0;
    while (i > 0) {
        digits[ix++] = i % 10;
        i /= 10;
    }
}

int main() {
    int n, d, i, max, lastDigit, sum, dp;
    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
    printf("Own digits power sums for N = 3 to 9 inclusive:\n");
    for (n = 3; n < 10; ++n) {
        for (d = 2; d < 10; ++d) powers[d] *= d;
        i = (int)pow(10, n-1);
        max = i * 10;
        lastDigit = 0;
        while (i < max) {
            if (!lastDigit) {
                getDigits(i);
                sum = 0;
                for (d = 0; d < n; ++d) {
                    dp = digits[d];
                    sum += powers[dp];
                }
            } else if (lastDigit == 1) {
                sum++;
            } else {
                sum += powers[lastDigit] - powers[lastDigit-1];
            }
            if (sum == i) {
                printf("%d\n", i);
                if (lastDigit == 0) printf("%d\n", i + 1);
                i += 10 - lastDigit;
                lastDigit = 0;
            } else if (sum > i) {
                i += 10 - lastDigit;
                lastDigit = 0;
            } else if (lastDigit < 9) {
                i++;
                lastDigit++;
            } else {
                i++;
                lastDigit = 0;
            }
        }
    }
    return 0;
}
Task: Compiler_Verifying syntax

C: 




#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <setjmp.h>

#define AT(CHAR) ( *pos == CHAR && ++pos )
#define TEST(STR) ( strncmp( pos, STR, strlen(STR) ) == 0 \
  && ! isalnum(pos[strlen(STR)]) && pos[strlen(STR)] != '_' )
#define IS(STR) ( TEST(STR) && (pos += strlen(STR)) )

static char *pos;                                 
static char *startpos;                            
static jmp_buf jmpenv;

static int
error(char *message)
  {
  printf("false  %s\n%*s^ %s\n", startpos, pos - startpos + 7, "", message);
  longjmp( jmpenv, 1 );
  }

static int
expr(int level)
  {
  while( isspace(*pos) ) ++pos;                     
  if( AT('(') )                                     
    {
    if( expr(0) && ! AT(')') ) error("missing close paren");
    }
  else if( level <= 4 && IS("not") && expr(6) ) { }
  else if( TEST("or") || TEST("and") || TEST("not") )
    {
    error("expected a primary, found an operator");
    }
  else if( isdigit(*pos) ) pos += strspn( pos, "0123456789" );
  else if( isalpha(*pos) ) pos += strspn( pos, "0123456789_"
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" );
  else error("expected a primary");

  do                    
    {
    while( isspace(*pos) ) ++pos;
    }
  while(
    level <= 2 && IS("or") ? expr(3) :
    level <= 3 && IS("and") ? expr(4) :
    level <= 4 && (AT('=') || AT('<')) ? expr(5) :
    level == 5 && (*pos == '=' || *pos == '<') ? error("non-associative") :
    level <= 6 && (AT('+') || AT('-')) ? expr(7) :
    level <= 7 && (AT('*') || AT('/')) ? expr(8) :
    0 );
  return 1;
  }

static void
parse(char *source)
  {
  startpos = pos = source;
  if( setjmp(jmpenv) ) return; 
  expr(0);
  if( *pos ) error("unexpected character following valid parse");
  printf(" true  %s\n", source);
  }

static char *tests[] = {
  "3 + not 5",
  "3 + (not 5)",
  "(42 + 3",
  "(42 + 3 some_other_syntax_error",
  "not 3 < 4 or (true or 3/4+8*5-5*2 < 56) and 4*3 < 12 or not true",
  "and 3 < 2",
  "not 7 < 2",
  "2 < 3 < 4",
  "2 < foobar - 3 < 4",
  "2 < foobar and 3 < 4",
  "4 * (32 - 16) + 9 = 73",
  "235 76 + 1",
  "a + b = not c and false",
  "a + b = (not c) and false",
  "a + b = (not c and false)",
  "ab_c / bd2 or < e_f7",
  "g not = h",
  "i++",
  "j & k",
  "l or _m",
  "wombat",
  "WOMBAT or monotreme",
  "a + b - c * d / e < f and not ( g = h )",
  "$",
  };

int
main(int argc, char *argv[])
  {
  for( int i = 0; i < sizeof(tests)/sizeof(*tests); i++ ) parse(tests[i]);
  }
Task: Colour pinstripe_Printer







Python: from turtle import *
from PIL import Image
import time
import subprocess



colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]

screen = getscreen()




inch_width = 11.0
inch_height = 8.5

pixels_per_inch = 100

pix_width = int(inch_width*pixels_per_inch)
pix_height = int(inch_height*pixels_per_inch)

screen.setup (width=pix_width, height=pix_height, startx=0, starty=0)

screen.screensize(pix_width,pix_height)





left_edge = -screen.window_width()//2

right_edge = screen.window_width()//2

bottom_edge = -screen.window_height()//2

top_edge = screen.window_height()//2



screen.delay(0)
screen.tracer(5)

for inch in range(int(inch_width)-1):
    line_width = inch + 1
    pensize(line_width)
    colornum = 0

    min_x = left_edge + (inch * pixels_per_inch)
    max_x = left_edge + ((inch+1) * pixels_per_inch)
    
    for y in range(bottom_edge,top_edge,line_width):
        penup()
        pencolor(colors[colornum])
        colornum = (colornum + 1) % len(colors)
        setposition(min_x,y)
        pendown()
        setposition(max_x,y)
         
screen.getcanvas().postscript(file="striped.eps")




im = Image.open("striped.eps")
im.save("striped.jpg")


    
subprocess.run(["mspaint", "/pt", "striped.jpg"])
Task: Native shebang







Python: 


import sys
print " ".join(sys.argv[1:])
Task: User input_Graphical







Python: from javax.swing import JOptionPane

def to_int(n, default=0):
    try:
        return int(n)
    except ValueError:
        return default

number = to_int(JOptionPane.showInputDialog ("Enter an Integer")) 
println(number)

a_string = JOptionPane.showInputDialog ("Enter a String")
println(a_string)
Task: Pascal's triangle_Puzzle







Python: 







def combine( snl, snr ):

	cl = {}
	if isinstance(snl, int):
		cl['1'] = snl
	elif isinstance(snl, string):
		cl[snl] = 1
	else:
		cl.update( snl)

	if isinstance(snr, int):
		n = cl.get('1', 0)
		cl['1'] = n + snr
	elif isinstance(snr, string):
		n = cl.get(snr, 0)
		cl[snr] = n + 1
	else:
		for k,v in snr.items():
			n = cl.get(k, 0)
			cl[k] = n+v
	return cl


def constrain(nsum, vn ):
	nn = {}
	nn.update(vn)
	n = nn.get('1', 0)
	nn['1'] = n - nsum
	return nn

def makeMatrix( constraints ):
	vmap = set()
	for c in constraints:
		vmap.update( c.keys())
	vmap.remove('1')
	nvars = len(vmap)
	vmap = sorted(vmap)		
	mtx = []
	for c in constraints:
		row = []
		for vv in vmap:
			row.append(float(c.get(vv, 0)))
		row.append(-float(c.get('1',0)))
		mtx.append(row)
	
	if len(constraints) == nvars:
		print 'System appears solvable'
	elif len(constraints) < nvars:
		print 'System is not solvable - needs more constraints.'
	return mtx, vmap


def SolvePyramid( vl, cnstr ):

	vl.reverse()
	constraints = [cnstr]
	lvls = len(vl)
	for lvln in range(1,lvls):
		lvd = vl[lvln]
		for k in range(lvls - lvln):
			sn = lvd[k]
			ll = vl[lvln-1]
			vn = combine(ll[k], ll[k+1])
			if sn is None:
				lvd[k] = vn
			else:
				constraints.append(constrain( sn, vn ))

	print 'Constraint Equations:'
	for cstr in constraints:
		fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
		print ' + '.join(fset), ' = 0'

	mtx,vmap = makeMatrix(constraints)

	MtxSolve(mtx)

	d = len(vmap)
	for j in range(d):
		print vmap[j],'=', mtx[j][d]


def MtxSolve(mtx):
	

	mDim = len(mtx)			
	for j in range(mDim):
		rw0= mtx[j]
		f = 1.0/rw0[j]
		for k in range(j, mDim+1):
			rw0[k] *= f
		
		for l in range(1+j,mDim):
			rwl = mtx[l]
			f = -rwl[j]
			for k in range(j, mDim+1):
				rwl[k] += f * rw0[k]

	
	for j1 in range(1,mDim):
		j = mDim - j1
		rw0= mtx[j]
		for l in range(0, j):
			rwl = mtx[l]
			f = -rwl[j]
			rwl[j]    += f * rw0[j]
			rwl[mDim] += f * rw0[mDim]

	return mtx


p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
Task: Fractal tree







Python: def setup():
    size(600, 600)
    background(0)
    stroke(255)
    drawTree(300, 550, 9)
    
def drawTree(x, y, depth):
    fork_ang = radians(20)
    base_len = 10
    if depth > 0:
        pushMatrix()
        translate(x, y - baseLen * depth)
        line(0, baseLen * depth, 0, 0)  
        rotate(fork_ang)
        drawTree(0, 0, depth - 1)  
        rotate(2 * -fork_ang)
        drawTree(0, 0, depth - 1) 
        popMatrix()
Task: Abbreviations, easy







Python: command_table_text = \


user_words = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"

def find_abbreviations_length(command_table_text):
    
    command_table = dict()
    for word in command_table_text.split():
        abbr_len = sum(1 for c in word if c.isupper())
        if abbr_len == 0:
            abbr_len = len(word)
        command_table[word] = abbr_len
    return command_table

def find_abbreviations(command_table):
    
    abbreviations = dict()
    for command, min_abbr_len in command_table.items():
        for l in range(min_abbr_len, len(command)+1):
            abbr = command[:l].lower()
            abbreviations[abbr] = command.upper()
    return abbreviations

def parse_user_string(user_string, abbreviations):
    user_words = [word.lower() for word in user_string.split()]
    commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
    return " ".join(commands)

command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)

full_words = parse_user_string(user_words, abbreviations_table)

print("user words:", user_words)
print("full words:", full_words)
Task: McNuggets problem







Python: >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
	nuggets.discard(6*s + 9*n + 20*t)

	
>>> max(nuggets)
43
>>>
Task: Include a file






PHP: include("file.php")
Task: Largest proper divisor of n

C: #include <stdio.h>

unsigned int lpd(unsigned int n) {
    if (n<=1) return 1;
    int i;
    for (i=n-1; i>0; i--)
        if (n%i == 0) return i;   
}

int main() {
    int i;
    for (i=1; i<=100; i++) {
        printf("%3d", lpd(i));
        if (i % 10 == 0) printf("\n");
    }
    return 0;
}
Task: Useless instructions

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

void uselessFunc(int uselessParam) { 
    auto int i; 

    if (true) {
        
    } else {
        printf("Never called\n");
    }

    for (i = 0; i < 0; ++i) {
        printf("Never called\n");
    }

    while (false) {
        printf("Never called\n");
    }

    printf(""); 

    return; 
}

struct UselessStruct {
    
};

int main() {
    uselessFunc(0);
    printf("Working OK.\n");
}
Task: Penta-power prime seeds

C: #include <stdio.h>
#include <stdbool.h>
#include <locale.h>
#include <gmp.h>

mpz_t p, p2, q;

bool isPentaPowerPrimeSeed(unsigned int n) {
    int i;
    mpz_set_ui(p, n);
    unsigned int k = n + 1;
    mpz_add_ui(p2, q, k);
    if (!mpz_probab_prime_p(p2, 15)) return false;
    mpz_add_ui(p2, p, k);
    if (!mpz_probab_prime_p(p2, 15)) return false;
    for (i = 0; i < 3; ++i) {
        mpz_mul_ui(p, p, n);
        mpz_set(p2, p);
        mpz_add_ui(p2, p2, k);
        if (!mpz_probab_prime_p(p2, 15)) return false;
    }
    return true;
}

const char *ord(int c) {
    int m = c % 100;
    if (m >= 4 && m <= 20) return "th";
    m %= 10;
    return (m == 1) ? "st" :
           (m == 2) ? "nd" :
           (m == 3) ? "rd" : "th";
}

int main() {
    unsigned int n;
    int c = 0, m = 1;
    mpz_init(p);
    mpz_init(p2);
    mpz_init_set_ui(q, 1);
    setlocale(LC_NUMERIC, "");
    printf("First thirty penta-power prime seeds:\n");
    for (n = 1; c < 30; n += 2) {
        if (isPentaPowerPrimeSeed(n)) {
            printf("%'9u ", n);
            if (!((++c) % 10)) printf("\n");
        }
    }

    n = 1;
    c = 0;
    printf("\nFirst penta-power prime seed greater than:\n");
    while (1) {
        if (isPentaPowerPrimeSeed(n)) {
            ++c;
            if (n > 1000000 * m) {
                printf(" %2d million is the %d%s: %'10u\n", m, c, ord(c), n);
                if (++m == 11) break;
            }
        }
        n += 2;
    }
    return 0;
}
Task: Quad-power prime seeds

C: #include <stdio.h>
#include <stdbool.h>
#include <locale.h>
#include <gmp.h>

mpz_t p, p2;

bool isQuadPowerPrimeSeed(unsigned int n) {
    int i;
    mpz_set_ui(p, n);
    unsigned int k = n + 1;
    mpz_add_ui(p2, p, k);
    if (!mpz_probab_prime_p(p2, 15)) return false;
    for (i = 0; i < 3; ++i) {
        mpz_mul_ui(p, p, n);
        mpz_set(p2, p);
        mpz_add_ui(p2, p2, k);
        if (!mpz_probab_prime_p(p2, 15)) return false;
    }
    return true;
}

const char *ord(int c) {
    int m = c % 100;
    if (m >= 4 && m <= 20) return "th";
    m %= 10;
    return (m == 1) ? "st" :
           (m == 2) ? "nd" :
           (m == 3) ? "rd" : "th";
}

int main() {
    unsigned int n;
    int c = 0, m = 1;
    mpz_init(p);
    mpz_init(p2);
    setlocale(LC_NUMERIC, "");
    printf("First fifty quad-power prime seeds:\n");
    for (n = 1; c < 50; ++n) {
        if (isQuadPowerPrimeSeed(n)) {
            printf("%'7u  ", n);
            if (!((++c) % 10)) printf("\n");
        }
    }

    printf("\nFirst quad-power prime seed greater than:\n");
    while (1) {
        if (isQuadPowerPrimeSeed(n)) {
            ++c;
            if (n > 1000000 * m) {
                printf(" %2d million is the %d%s: %'10u\n", m, c, ord(c), n);
                if (++m == 11) break;
            }
        }
        ++n;
    }
    return 0;
}
Task: Trabb Pardo–Knuth algorithm








VB: Function tpk(s)
	arr = Split(s," ")
	For i = UBound(arr) To 0 Step -1
		n = fx(CDbl(arr(i)))
		If  n > 400 Then
			WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
		Else
			WScript.StdOut.WriteLine arr(i) & " = " & n
		End If
	Next
End Function

Function fx(x)
	fx = Sqr(Abs(x))+5*x^3
End Function


WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
Task: Playing cards








VB: class playingcard
	dim suit
	dim pips
end class

class carddeck
	private suitnames
	private pipnames
	private cardno
	private deck(52)
	private nTop
	
	sub class_initialize
		dim suit
		dim pips
		suitnames = split("H,D,C,S",",")
		pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",")
		cardno = 0

		for suit = 1 to 4
			for pips = 1 to 13
				set deck(cardno) = new playingcard
				deck(cardno).suit = suitnames(suit-1)
				deck(cardno).pips = pipnames(pips-1)
				cardno = cardno + 1
			next
		next
		nTop = 0
	end sub
	
	public sub showdeck
		dim a
		redim a(51-nTop)
		for i = nTop to 51
			a(i) = deck(i).pips & deck(i).suit  
		next
		wscript.echo join( a, ", ")
	end sub
	
	public sub shuffle
		dim r
		randomize timer
		for i = nTop to 51
			r = int( rnd * ( 52 - nTop ) ) 
			if r <> i then
				objswap deck(i),deck(r)
			end if
		next
	end sub

	public function deal()
		set deal = deck( nTop )
		nTop = nTop + 1
	end function

	public property get cardsRemaining
		cardsRemaining = 52 - nTop
	end property
	
	private sub objswap(   a,   b )
		dim tmp
		set tmp = a
		set a = b
		set b = tmp
	end sub
end class
Task: Longest increasing subsequence








VB: Function LIS(arr)
	n = UBound(arr)
	Dim p()
	ReDim p(n)
	Dim m()
	ReDim m(n)
	l = 0
	For i = 0 To n
		lo = 1
		hi = l
		Do While lo <= hi
			middle = Int((lo+hi)/2)
			If arr(m(middle)) < arr(i) Then
				lo = middle + 1
			Else
				hi = middle - 1
			End If
		Loop
		newl = lo
		p(i) = m(newl-1)
		m(newl) = i
		If newL > l Then
			l = newl
		End If
	Next
	Dim s()
	ReDim s(l)
	k = m(l)
	For i = l-1 To 0 Step - 1
		s(i) = arr(k)
		k = p(k)
	Next
	LIS = Join(s,",")
End Function

WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))
WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
Task: Type detection








VB: Public Sub main()
    Dim c(1) As Currency
    Dim d(1) As Double
    Dim dt(1) As Date
    Dim a(1) As Integer
    Dim l(1) As Long
    Dim s(1) As Single
    Dim e As Variant
    Dim o As Object
    Set o = New Application
    Debug.Print TypeName(o)
    Debug.Print TypeName(1 = 1)
    Debug.Print TypeName(CByte(1))
    Set o = New Collection
    Debug.Print TypeName(o)
    Debug.Print TypeName(1@)
    Debug.Print TypeName(c)
    Debug.Print TypeName(CDate(1))
    Debug.Print TypeName(dt)
    Debug.Print TypeName(CDec(1))
    Debug.Print TypeName(1#)
    Debug.Print TypeName(d)
    Debug.Print TypeName(e)
    Debug.Print TypeName(CVErr(1))
    Debug.Print TypeName(1)
    Debug.Print TypeName(a)
    Debug.Print TypeName(1&)
    Debug.Print TypeName(l)
    Set o = Nothing
    Debug.Print TypeName(o)
    Debug.Print TypeName([A1])
    Debug.Print TypeName(1!)
    Debug.Print TypeName(s)
    Debug.Print TypeName(CStr(1))
    Debug.Print TypeName(Worksheets(1))
End Sub
Task: Minesweeper game








VB: Option Explicit

Public vTime As Single
Public PlaysCount As Long

Sub Main_MineSweeper()
Dim Userf As New cMinesweeper

    
    
    Userf.Show 0, True
End Sub
Task: Arithmetic-geometric mean_Calculate Pi








VB: Imports System, System.Numerics

Module Program
    Function IntSqRoot(ByVal valu As BigInteger, ByVal guess As BigInteger) As BigInteger
        Dim term As BigInteger : Do
            term = valu / guess
            If BigInteger.Abs(term - guess) <= 1 Then Exit Do
            guess += term : guess >>= 1
        Loop While True : Return guess
    End Function

    Function ISR(ByVal term As BigInteger, ByVal guess As BigInteger) As BigInteger
        Dim valu As BigInteger = term * guess : Do
            If BigInteger.Abs(term - guess) <= 1 Then Exit Do
            guess += term : guess >>= 1 : term = valu / guess
        Loop While True : Return guess
    End Function

    Function CalcAGM(ByVal lam As BigInteger, ByVal gm As BigInteger, ByRef z As BigInteger,
                     ByVal ep As BigInteger) As BigInteger
        Dim am, zi As BigInteger : Dim n As ULong = 1 : Do
            am = (lam + gm) >> 1 : gm = ISR(lam, gm)
            Dim v As BigInteger = am - lam
            zi = v * v * n : If zi < ep Then Exit Do
            z -= zi : n <<= 1 : lam = am
        Loop While True : Return am
    End Function

    Function BIP(ByVal exp As Integer, ByVal Optional man As ULong = 1) As BigInteger
        Dim rv As BigInteger = BigInteger.Pow(10, exp) : Return If(man = 1, rv, man * rv)
    End Function

    Sub Main(args As String())
        Dim d As Integer = 25000
        If args.Length > 0 Then
            Integer.TryParse(args(0), d)
            If d < 1 OrElse d > 999999 Then d = 25000
        End If
        Dim st As DateTime = DateTime.Now
        Dim am As BigInteger = BIP(d),
            gm As BigInteger = IntSqRoot(BIP(d + d - 1, 5),
                                         BIP(d - 15, Math.Sqrt(0.5) * 1.0E+15)),
             z As BigInteger = BIP(d + d - 2, 25),
             agm As BigInteger = CalcAGM(am, gm, z, BIP(d + 1)),
             pi As BigInteger = agm * agm * BIP(d - 2) / z
        Console.WriteLine("Computation time: {0:0.0000} seconds ",
                          (DateTime.Now - st).TotalMilliseconds / 1000)
        If args.Length > 1 OrElse d <= 1000 Then
            Dim s As String = pi.ToString()
            Console.WriteLine("{0}.{1}", s(0), s.Substring(1))
        End If
        If Diagnostics.Debugger.IsAttached Then Console.ReadKey()
    End Sub
End Module
Task: Cuban primes








VB: Module Module1
    Dim primes As List(Of Long) = {3L, 5L}.ToList()

    Sub Main(args As String())
        Const cutOff As Integer = 200, bigUn As Integer = 100000,
              tn As String = " cuban prime"
        Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn)
        Dim c As Integer = 0, showEach As Boolean = True, skip As Boolean = True,
            v As Long = 0, st As DateTime = DateTime.Now
        For i As Long = 1 To Long.MaxValue
            v = 3 * i : v = v * i + v + 1
            Dim found As Boolean = False, mx As Integer = Math.Ceiling(Math.Sqrt(v))
            For Each item In primes
                If item > mx Then Exit For
                If v Mod item = 0 Then found = True : Exit For
            Next : If Not found Then
                c += 1 : If showEach Then
                    For z = primes.Last + 2 To v - 2 Step 2
                        Dim fnd As Boolean = False
                        For Each item In primes
                            If item > mx Then Exit For
                            If z Mod item = 0 Then fnd = True : Exit For
                        Next : If Not fnd Then primes.Add(z)
                    Next : primes.Add(v) : Console.Write("{0,11:n0}", v)
                    If c Mod 10 = 0 Then Console.WriteLine()
                    If c = cutOff Then showEach = False
                Else
                    If skip Then skip = False : i += 772279 : c = bigUn - 1
                End If
                If c = bigUn Then Exit For
            End If
        Next
        Console.WriteLine("{1}The {2:n0}th{3} is {0,17:n0}", v, vbLf, c, tn)
        Console.WriteLine("Computation time was {0} seconds", (DateTime.Now - st).TotalSeconds)
        If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
    End Sub
End Module