WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Permutation sort

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

typedef int(*cmp_func)(const void*, const void*);

void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
	char *p, *q, *tmp = malloc(msize);
#	define A(i) ((char *)a + msize * (i))
#	define swap(a, b) {\
		memcpy(tmp, a, msize);\
		memcpy(a, b, msize);\
		memcpy(b, tmp, msize);	}
	while (1) {
		
		for (p = A(n - 1); (void*)p > a; p = q)
			if (_cmp(q = p - msize, p) > 0)
				break;

		if ((void*)p <= a) break;

		
		for (p = A(n - 1); p > q; p-= msize)
			if (_cmp(q, p) > 0) break;

		swap(p, q); 
		
		for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)
			swap(p, q);
	}
	free(tmp);
}

int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }

int main()
{
	int i;
	const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" };
	perm_sort(strs, 5, sizeof(*strs), scmp);

	for (i = 0; i < 5; i++)
		printf("%s\n", strs[i]);
	return 0;
}




Go: package main

import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}


func main() {
    fmt.Println("before:", a)
    if len(a) > 1 && !recurse(len(a) - 1) {
        
        
        
        
        panic("sorted permutation not found!")
    }
    fmt.Println("after: ", a)
}


func recurse(last int) bool {
    if last <= 0 {
        
        for i := len(a) - 1; a[i] >= a[i-1]; i-- {
            if i == 1 {
                return true
            }
        }
        return false
    }
    for i := 0; i <= last; i++ {
        a[i], a[last] = a[last], a[i]
        if recurse(last - 1) {
            return true
        }
        a[i], a[last] = a[last], a[i]
    }
    return false
}
Task: Averages_Arithmetic mean

C: #include <stdio.h>

double mean(double *v, int len)
{
	double sum = 0;
	int i;
	for (i = 0; i < len; i++)
		sum += v[i];
	return sum / len;
}

int main(void)
{
	double v[] = {1, 2, 2.718, 3, 3.142};
	int i, len;
	for (len = 5; len >= 0; len--) {
		printf("mean[");
		for (i = 0; i < len; i++)
			printf(i ? ", %g" : "%g", v[i]);
		printf("] = %g\n", mean(v, len));
	}

	return 0;
}




Go: package main

import (
    "fmt"
    "math"
)

func mean(v []float64) (m float64, ok bool) {
    if len(v) == 0 {
        return
    }
    
    
    var parts []float64
    for _, x := range v {
        var i int
        for _, p := range parts {
            sum := p + x
            var err float64
            switch ax, ap := math.Abs(x), math.Abs(p); {
            case ax < ap:
                err = x - (sum - p)
            case ap < ax:
                err = p - (sum - x)
            }
            if err != 0 {
                parts[i] = err
                i++
            }
            x = sum
        }
        parts = append(parts[:i], x)
    }
    var sum float64
    for _, x := range parts {
        sum += x
    }
    return sum / float64(len(v)), true
}

func main() {
    for _, v := range [][]float64{
        []float64{},                         
        []float64{math.Inf(1), math.Inf(1)}, 

        
        
        []float64{math.Inf(1), math.Inf(-1)},

        []float64{3, 1, 4, 1, 5, 9},

        
        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},

        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
    } {
        fmt.Println("Vector:", v)
        if m, ok := mean(v); ok {
            fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
        } else {
            fmt.Println("Mean undefined\n")
        }
    }
}
Task: Entropy

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
 
#define MAXLEN 100 
 
int makehist(unsigned char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}
 
double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}
 
int main(void){
	unsigned char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	scanf("%[^\n]",S);
	len=strlen(S);
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);
	
	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}




Go: package main

import (
    "fmt"
    "math"
    "strings"
)

func main(){
    fmt.Println(H("1223334444"))
}


func H(data string) (entropy float64) {
    if data == "" {
        return 0
    }
    for i := 0; i < 256; i++ {
        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
        if px > 0 {
	    entropy += -px * math.Log2(px)
	}
    }
    return entropy
}
Task: Tokenize a string with escaping

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

#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'

typedef char* Str; 


unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );



int main() {
    char s[] = STR_DEMO;
    unsigned int i, q;

    Str *list = Tokenize( s, SEP, ESC, &q );

    if( list != NULL ) {
        printf( "\n Original string: %s\n\n", STR_DEMO );
        printf( " %d tokens:\n\n", q );

        for( i=0; i<q; ++i )
            printf( " %4d. %s\n", i+1, list[i] );

        free( list );
    }

    return 0;
}



unsigned int ElQ( const char *s, char sep, char esc ) {
    unsigned int q, e;
    const char *p;

    for( e=0, q=1, p=s; *p; ++p ) {
        if( *p == esc )
            e = !e;
        else if( *p == sep )
            q += !e;
        else e = 0;
    }

    return q;
}



Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
    Str *list = NULL;

    *q = ElQ( s, sep, esc );
    list = malloc( *q * sizeof(Str) );

    if( list != NULL ) {
        unsigned int e, i;
        char *p;

        i = 0;
        list[i++] = s;

        for( e=0, p=s; *p; ++p ) {
            if( *p == esc ) {
                e = !e;
            }
            else if( *p == sep && !e ) {
                list[i++] = p+1;
                *p = '\0';
            }
            else {
                e = 0;
            }
        }
    }

    return list;
}




Go: package main

import (
	"errors"
	"fmt"
)

func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
	var runes []rune
	inEscape := false
	for _, r := range s {
		switch {
		case inEscape:
			inEscape = false
			fallthrough
		default:
			runes = append(runes, r)
		case r == escape:
			inEscape = true
		case r == sep:
			tokens = append(tokens, string(runes))
			runes = runes[:0]
		}
	}
	tokens = append(tokens, string(runes))
	if inEscape {
		err = errors.New("invalid terminal escape")
	}
	return tokens, err
}

func main() {
	const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
	const separator = '|'
	const escape = '^'

	fmt.Printf("Input:   %q\n", sample)
	tokens, err := TokenizeString(sample, separator, escape)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Printf("Tokens: %q\n", tokens)
	}
}
Task: Hello world_Text

C: const hello = "Hello world!\n"

print(hello)




Go: package main

import "fmt"

func main() { fmt.Println("Hello world!") }
Task: Forward difference

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

double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
	unsigned int i, j;
	double* y;

	
	if (order >= len) return 0;

	y = malloc(sizeof(double) * len);
	if (!order) {
		memcpy(y, x, sizeof(double) * len);
		return y;
	}

	
	for (j = 0; j < order; j++, x = y)
		for (i = 0, len--; i < len; i++)
			y[i] = x[i + 1] - x[i];

	y = realloc(y, sizeof(double) * len);
	return y;
}

int main(void)
{
	double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
	int i, len = sizeof(x) / sizeof(x[0]);

	y = fwd_diff(x, len, 1);
	for (i = 0; i < len - 1; i++)
		printf("%g ", y[i]);
	putchar('\n');

	return 0;
}




Go: package main

import "fmt"

func main() {
    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
    fmt.Println(a)
    fmt.Println(fd(a, 9))
}

func fd(a []int, ord int) []int {
    for i := 0; i < ord; i++ {
        for j := 0; j < len(a)-i-1; j++ {
            a[j] = a[j+1] - a[j]
        }
    }
    return a[:len(a)-ord]
}
Task: Primality by trial division

C: int is_prime(unsigned int n)
{
	unsigned int p;
	if (!(n & 1) || n < 2 ) return n == 2;

	
	for (p = 3; p <= n/p; p += 2)
		if (!(n % p)) return 0;
	return 1;
}




Go: func IsPrime(n int) bool {
	if n < 0 { n = -n }
	switch {
        case n == 2:
		return true
	case n < 2 || n % 2 == 0:
		return false
	
	default:
		for i = 3; i*i <= n; i += 2 {
			if n % i == 0 { return false }
		}
	}
	return true
}
Task: Evaluate binomial coefficients

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



static unsigned long gcd_ui(unsigned long x, unsigned long y) {
  unsigned long t;
  if (y < x) { t = x; x = y; y = t; }
  while (y > 0) {
    t = y;  y = x % y;  x = t;  
  }
  return x;
}

unsigned long binomial(unsigned long n, unsigned long k) {
  unsigned long d, g, r = 1;
  if (k == 0) return 1;
  if (k == 1) return n;
  if (k >= n) return (k == n);
  if (k > n/2) k = n-k;
  for (d = 1; d <= k; d++) {
    if (r >= ULONG_MAX/n) {  
      unsigned long nr, dr;  
      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;
      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;
      if (r >= ULONG_MAX/nr) return 0;  
      r *= nr;
      r /= dr;
      n--;
    } else {
      r *= n--;
      r /= d;
    }
  }
  return r;
}

int main() {
    printf("%lu\n", binomial(5, 3));
    printf("%lu\n", binomial(40, 19));
    printf("%lu\n", binomial(67, 31));
    return 0;
}




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

func main() {
  fmt.Println(new(big.Int).Binomial(5, 3))
  fmt.Println(new(big.Int).Binomial(60, 30))
}
Task: Collections

C: #define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) 
int ar[10];               
ar[0] = 1;                
ar[1] = 2;

int* p;                   
for (p=ar;                
       p<(ar+cSize(ar));  
       p++) {             
  printf("%d\n",*p);      
}                         




Go: package main

import "fmt"

func main() {
    var a []interface{}
    a = append(a, 3)
    a = append(a, "apples", "oranges")
    fmt.Println(a)
}
Task: Singly-linked list_Traversal

C: struct link *first;

struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
  
}




Go: start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
    fmt.Println(iter)
}
Task: Bitmap_Write a PPM file

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

int main(void)
{
  const int dimx = 800, dimy = 800;
  int i, j;
  FILE *fp = fopen("first.ppm", "wb"); 
  (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
  for (j = 0; j < dimy; ++j)
  {
    for (i = 0; i < dimx; ++i)
    {
      static unsigned char color[3];
      color[0] = i % 256;  
      color[1] = j % 256;  
      color[2] = (i * j) % 256;  
      (void) fwrite(color, 1, 3, fp);
    }
  }
  (void) fclose(fp);
  return EXIT_SUCCESS;
}




Go: package raster

import (
    "fmt"
    "io"
    "os"
)


func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
    
    if _, err = fmt.Fprintln(w, "P6"); err != nil {
        return
    }

    
    for _, c := range b.Comments {
        if _, err = fmt.Fprintln(w, c); err != nil {
            return
        }
    }

    
    _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
    if err != nil {
        return
    }

    
    b3 := make([]byte, 3*len(b.px))
    n1 := 0
    for _, px := range b.px {
        b3[n1] = px.R
        b3[n1+1] = px.G
        b3[n1+2] = px.B
        n1 += 3
    }
    if _, err = w.Write(b3); err != nil {
        return
    }
    return
}


func (b *Bitmap) WritePpmFile(fn string) (err error) {
    var f *os.File
    if f, err = os.Create(fn); err != nil {
        return
    }
    if err = b.WritePpmTo(f); err != nil {
        return
    }
    return f.Close()
}
Task: Delete a file

C: #include <stdio.h>

int main() {
  remove("input.txt");
  remove("/input.txt");
  remove("docs");
  remove("/docs");
  return 0;
}




Go: package main
import "os"

func main() {
  os.Remove("input.txt")
  os.Remove("/input.txt")
  os.Remove("docs")
  os.Remove("/docs")
  
  os.RemoveAll("docs")
  os.RemoveAll("/docs")
}
Task: Hickerson series of almost integers

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

void h(int n)
{
	MPFR_DECL_INIT(a, 200);
	MPFR_DECL_INIT(b, 200);

	mpfr_fac_ui(a, n, MPFR_RNDD);		

	mpfr_set_ui(b, 2, MPFR_RNDD);		
	mpfr_log(b, b, MPFR_RNDD);		
	mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);	

	mpfr_div(a, a, b, MPFR_RNDD);		
	mpfr_div_ui(a, a, 2, MPFR_RNDD);	

	mpfr_frac(b, a, MPFR_RNDD);		
	mpfr_printf("%2d: %23.4Rf  %c\n", n, a,
		mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}

int main(void)
{
	int n;
	for (n = 1; n <= 17; n++) h(n);

	return 0;
}




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
    h := big.NewRat(1, 2)
    h.Quo(h, ln2)
    var f big.Rat
    var w big.Int
    for i := int64(1); i <= 17; i++ {
        h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
        w.Quo(h.Num(), h.Denom())
        f.Sub(h, f.SetInt(&w))
        y, _ := f.Float64()
        d := fmt.Sprintf("%.3f", y)
        fmt.Printf("n: %2d  h: %18d%s  Nearly integer: %t\n",
            i, &w, d[1:], d[2] == '0' || d[2] == '9')
    }
}
Task: Average loop length

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

#define MAX_N 20
#define TIMES 1000000

double factorial(int n) {
	double f = 1;
	int i;
	for (i = 1; i <= n; i++) f *= i;
	return f;
}

double expected(int n) {
	double sum = 0;
	int i;
	for (i = 1; i <= n; i++)
		sum += factorial(n) / pow(n, i) / factorial(n - i);
	return sum;
}

int randint(int n) {
	int r, rmax = RAND_MAX / n * n;
	while ((r = rand()) >= rmax);
	return r / (RAND_MAX / n);
}

int test(int n, int times) {
	int i, count = 0;
	for (i = 0; i < times; i++) {
		int x = 1, bits = 0;
		while (!(bits & x)) {
			count++;
			bits |= x;
			x = 1 << randint(n);
		}
	}
	return count;
}

int main(void) {
	srand(time(0));
	puts(" n\tavg\texp.\tdiff\n-------------------------------");

	int n;
	for (n = 1; n <= MAX_N; n++) {
		int cnt = test(n, TIMES);
		double avg = (double)cnt / TIMES;
		double theory = expected(n);
		double diff = (avg / theory - 1) * 100;
		printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
	}
	return 0;
}




Go: package main

import (
    "fmt"
    "math"
    "math/rand"
)

const nmax = 20

func main() {
    fmt.Println(" N    average    analytical    (error)")
    fmt.Println("===  =========  ============  =========")
    for n := 1; n <= nmax; n++ {
        a := avg(n)
        b := ana(n)
        fmt.Printf("%3d  %9.4f  %12.4f  (%6.2f%%)\n",
            n, a, b, math.Abs(a-b)/b*100)
    }
}

func avg(n int) float64 {
    const tests = 1e4
    sum := 0
    for t := 0; t < tests; t++ {
        var v [nmax]bool
        for x := 0; !v[x]; x = rand.Intn(n) {
            v[x] = true
            sum++
        }
    }
    return float64(sum) / tests
}

func ana(n int) float64 {
    nn := float64(n)
    term := 1.
    sum := 1.
    for i := nn - 1; i >= 1; i-- {
        term *= i / nn
        sum += term
    }
    return sum
}
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}




Go: package main

import (
    "fmt"
)

func main() {
    str := "Mary had a %s lamb"
    txt := "little"
    out := fmt.Sprintf(str, txt)
    fmt.Println(out)
}
Task: Sorting algorithms_Patience sort

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

int* patienceSort(int* arr,int size){
	int decks[size][size],i,j,min,pickedRow;
	
	int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));
	
	for(i=0;i<size;i++){
		for(j=0;j<size;j++){
			if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){
				decks[j][count[j]] = arr[i];
				count[j]++;
				break;
			}
		}
	}
	
	min = decks[0][count[0]-1];
	pickedRow = 0;
	
	for(i=0;i<size;i++){
		for(j=0;j<size;j++){
			if(count[j]>0 && decks[j][count[j]-1]<min){
				min = decks[j][count[j]-1];
				pickedRow = j;
			}
		}
		sortedArr[i] = min;
		count[pickedRow]--;
		
		for(j=0;j<size;j++)
			if(count[j]>0){
				min = decks[j][count[j]-1];
				pickedRow = j;
				break;
			}
	}
	
	free(count);
	free(decks);
	
	return sortedArr;
}

int main(int argC,char* argV[])
{
	int *arr, *sortedArr, i;
	
	if(argC==0)
		printf("Usage : %s <integers to be sorted separated by space>");
	else{
		arr = (int*)malloc((argC-1)*sizeof(int));
		
		for(i=1;i<=argC;i++)
			arr[i-1] = atoi(argV[i]);
		
		sortedArr = patienceSort(arr,argC-1);
		
		for(i=0;i<argC-1;i++)
			printf("%d ",sortedArr[i]);
	}
	
	return 0;
}




Go: package main

import (
  "fmt"
  "container/heap"
  "sort"
)

type IntPile []int
func (self IntPile) Top() int { return self[len(self)-1] }
func (self *IntPile) Pop() int {
    x := (*self)[len(*self)-1]
    *self = (*self)[:len(*self)-1]
    return x
}

type IntPilesHeap []IntPile
func (self IntPilesHeap) Len() int { return len(self) }
func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }
func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }
func (self *IntPilesHeap) Pop() interface{} {
    x := (*self)[len(*self)-1]
    *self = (*self)[:len(*self)-1]
    return x
}

func patience_sort (n []int) {
  var piles []IntPile
  
  for _, x := range n {
    j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })
    if j != len(piles) {
      piles[j] = append(piles[j], x)
    } else {
      piles = append(piles, IntPile{ x })
    }
  }

  
  hp := IntPilesHeap(piles)
  heap.Init(&hp)
  for i, _ := range n {
    smallPile := heap.Pop(&hp).(IntPile)
    n[i] = smallPile.Pop()
    if len(smallPile) != 0 {
      heap.Push(&hp, smallPile)
    }
  }
  if len(hp) != 0 {
    panic("something went wrong")
  }
}

func main() {
    a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}
    patience_sort(a)
    fmt.Println(a)
}
Task: Tau number

C: #include <stdio.h>

unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    unsigned int p;

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

int main() {
    const unsigned int limit = 100;
    unsigned int count = 0;
    unsigned int n;

    printf("The first %d tau numbers are:\n", limit);
    for (n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            printf("%6d", n);
            ++count;
            if (count % 10 == 0) {
                printf("\n");
            }
        }
    }

    return 0;
}




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 first 100 tau numbers are:")
    count := 0
    i := 1
    for count < 100 {
        tf := countDivisors(i)
        if i%tf == 0 {
            fmt.Printf("%4d  ", i)
            count++
            if count%10 == 0 {
                fmt.Println()
            }
        }
        i++
    }
}
Task: Determinant and permanent

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

double det_in(double **in, int n, int perm)
{
	if (n == 1) return in[0][0];

	double sum = 0, *m[--n];
	for (int i = 0; i < n; i++)
		m[i] = in[i + 1] + 1;

	for (int i = 0, sgn = 1; i <= n; i++) {
		sum += sgn * (in[i][0] * det_in(m, n, perm));
		if (i == n) break;

		m[i] = in[i] + 1;
		if (!perm) sgn = -sgn;
	}
	return sum;
}


double det(double *in, int n, int perm)
{
	double *m[n];
	for (int i = 0; i < n; i++)
		m[i] = in + (n * i);

	return det_in(m, n, perm);
}

int main(void)
{
	double x[] = {	0, 1, 2, 3, 4,
			5, 6, 7, 8, 9,
			10, 11, 12, 13, 14,
			15, 16, 17, 18, 19,
			20, 21, 22, 23, 24 };

	printf("det:  %14.12g\n", det(x, 5, 0));
	printf("perm: %14.12g\n", det(x, 5, 1));

	return 0;
}




Go: package main

import (
    "fmt"
    "permute"
)

func determinant(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += float64(s) * pr
    }
    return
}

func permanent(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += pr
    }
    return
}

var m2 = [][]float64{
    {1, 2},
    {3, 4}}

var m3 = [][]float64{
    {2, 9, 4},
    {7, 5, 3},
    {6, 1, 8}}

func main() {
    fmt.Println(determinant(m2), permanent(m2))
    fmt.Println(determinant(m3), permanent(m3))
}
Task: Partition function P

C: #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <gmp.h>

mpz_t* partition(uint64_t n) {
	mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
	mpz_init_set_ui(pn[0], 1);
	mpz_init_set_ui(pn[1], 1);
	for (uint64_t i = 2; i < n + 2; i ++) {
		mpz_init(pn[i]);
		for (uint64_t k = 1, penta; ; k++) {
			penta = k * (3 * k - 1) >> 1;
			if (penta >= i) break;
			if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
			else mpz_sub(pn[i], pn[i], pn[i - penta]);
			penta += k;
			if (penta >= i) break;
			if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
			else mpz_sub(pn[i], pn[i], pn[i - penta]);
		}
	}
	mpz_t *tmp = &pn[n + 1];
	for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);
	free(pn);
	return tmp;
}

int main(int argc, char const *argv[]) {
	clock_t start = clock();
	mpz_t *p = partition(6666);
	gmp_printf("%Zd\n", p);
	printf("Elapsed time: %.04f seconds\n",
		(double)(clock() - start) / (double)CLOCKS_PER_SEC);
	return 0;
}




Go: package main

import (
    "fmt"
    "math/big"
    "time"
)

var p []*big.Int
var pd []int

func partDiffDiff(n int) int {
    if n&1 == 1 {
        return (n + 1) / 2
    }
    return n + 1
}

func partDiff(n int) int {
    if n < 2 {
        return 1
    }
    pd[n] = pd[n-1] + partDiffDiff(n-1)
    return pd[n]
}

func partitionsP(n int) {
    if n < 2 {
        return
    }
    psum := new(big.Int)
    for i := 1; i <= n; i++ {
        pdi := partDiff(i)
        if pdi > n {
            break
        }
        sign := int64(-1)
        if (i-1)%4 < 2 {
            sign = 1
        }
        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))
        psum.Add(psum, t)
    }
    p[n] = psum
}

func main() {
    start := time.Now()
    const N = 6666
    p = make([]*big.Int, N+1)
    pd = make([]int, N+1)
    p[0], pd[0] = big.NewInt(1), 1
    p[1], pd[1] = big.NewInt(1), 1
    for n := 2; n <= N; n++ {
        partitionsP(n)
    }
    fmt.Printf("p[%d)] = %d\n", N, p[N])
    fmt.Printf("Took %s\n", time.Since(start))
}