Four is the number of letters in the ...

#include <ctype.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>

typedef uint64_t integer;

typedef struct number_names_tag {
    const char* cardinal;
    const char* ordinal;
} number_names;

const number_names small[] = {
    { "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
    { "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
    { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
    { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
    { "twelve", "twelfth" }, { "thirteen", "thirteenth" },
    { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
    { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
    { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};

const number_names tens[] = {
    { "twenty", "twentieth" }, { "thirty", "thirtieth" },
    { "forty", "fortieth" }, { "fifty", "fiftieth" },
    { "sixty", "sixtieth" }, { "seventy", "seventieth" },
    { "eighty", "eightieth" }, { "ninety", "ninetieth" }
};

typedef struct named_number_tag {
    const char* cardinal;
    const char* ordinal;
    integer number;
} named_number;

const named_number named_numbers[] = {
    { "hundred", "hundredth", 100 },
    { "thousand", "thousandth", 1000 },
    { "million", "millionth", 1000000 },
    { "billion", "biliionth", 1000000000 },
    { "trillion", "trillionth", 1000000000000 },
    { "quadrillion", "quadrillionth", 1000000000000000ULL },
    { "quintillion", "quintillionth", 1000000000000000000ULL }
};

const char* get_small_name(const number_names* n, bool ordinal) {
    return ordinal ? n->ordinal : n->cardinal;
}

const char* get_big_name(const named_number* n, bool ordinal) {
    return ordinal ? n->ordinal : n->cardinal;
}

const named_number* get_named_number(integer n) {
    const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
    for (size_t i = 0; i + 1 < names_len; ++i) {
        if (n < named_numbers[i + 1].number)
            return &named_numbers[i];
    }
    return &named_numbers[names_len - 1];
}

typedef struct word_tag {
    size_t offset;
    size_t length;
} word_t;

typedef struct word_list_tag {
    GArray* words;
    GString* str;
} word_list;

void word_list_create(word_list* words) {
    words->words = g_array_new(FALSE, FALSE, sizeof(word_t));
    words->str = g_string_new(NULL);
}

void word_list_destroy(word_list* words) {
    g_string_free(words->str, TRUE);
    g_array_free(words->words, TRUE);
}

void word_list_clear(word_list* words) {
    g_string_truncate(words->str, 0);
    g_array_set_size(words->words, 0);
}

void word_list_append(word_list* words, const char* str) {
    size_t offset = words->str->len;
    size_t len = strlen(str);
    g_string_append_len(words->str, str, len);
    word_t word;
    word.offset = offset;
    word.length = len;
    g_array_append_val(words->words, word);
}

word_t* word_list_get(word_list* words, size_t index) {
    return &g_array_index(words->words, word_t, index);
}

void word_list_extend(word_list* words, const char* str) {
    word_t* word = word_list_get(words, words->words->len - 1);
    size_t len = strlen(str);
    word->length += len;
    g_string_append_len(words->str, str, len);
}

size_t append_number_name(word_list* words, integer n, bool ordinal) {
    size_t count = 0;
    if (n < 20) {
        word_list_append(words, get_small_name(&small[n], ordinal));
        count = 1;
    } else if (n < 100) {
        if (n % 10 == 0) {
            word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));
        } else {
            word_list_append(words, get_small_name(&tens[n/10 - 2], false));
            word_list_extend(words, "-");
            word_list_extend(words, get_small_name(&small[n % 10], ordinal));
        }
        count = 1;
    } else {
        const named_number* num = get_named_number(n);
        integer p = num->number;
        count += append_number_name(words, n/p, false);
        if (n % p == 0) {
            word_list_append(words, get_big_name(num, ordinal));
            ++count;
        } else {
            word_list_append(words, get_big_name(num, false));
            ++count;
            count += append_number_name(words, n % p, ordinal);
        }
    }
    return count;
}

size_t count_letters(word_list* words, size_t index) {
    const word_t* word = word_list_get(words, index);
    size_t letters = 0;
    const char* s = words->str->str + word->offset;
    for (size_t i = 0, n = word->length; i < n; ++i) {
        if (isalpha((unsigned char)s[i]))
            ++letters;
    }
    return letters;
}

void sentence(word_list* result, size_t count) {
    static const char* words[] = {
        "Four", "is", "the", "number", "of", "letters", "in", "the",
        "first", "word", "of", "this", "sentence,"
    };
    word_list_clear(result);
    size_t n = sizeof(words)/sizeof(words[0]);
    for (size_t i = 0; i < n; ++i)
        word_list_append(result, words[i]);
    for (size_t i = 1; count > n; ++i) {
        n += append_number_name(result, count_letters(result, i), false);
        word_list_append(result, "in");
        word_list_append(result, "the");
        n += 2;
        n += append_number_name(result, i + 1, true);

        word_list_extend(result, ",");
    }
}

size_t sentence_length(const word_list* words) {
    size_t n = words->words->len;
    if (n == 0)
        return 0;
    return words->str->len + n - 1;
}

int main() {
    setlocale(LC_ALL, "");
    size_t n = 201;
    word_list result = { 0 };
    word_list_create(&result);
    sentence(&result, n);
    printf("Number of letters in first %'lu words in the sequence:\n", n);
    for (size_t i = 0; i < n; ++i) {
        if (i != 0)
            printf("%c", i % 25 == 0 ? '\n' : ' ');
        printf("%'2lu", count_letters(&result, i));
    }
    printf("\nSentence length: %'lu\n", sentence_length(&result));
    for (n = 1000; n <= 10000000; n *= 10) {
        sentence(&result, n);
        const word_t* word = word_list_get(&result, n - 1);
        const char* s = result.str->str + word->offset;
        printf("The %'luth word is '%.*s' and has %lu letters. ", n,
               (int)word->length, s, count_letters(&result, n - 1));
        printf("Sentence length: %'lu\n" , sentence_length(&result));
    }
    word_list_destroy(&result);
    return 0;
}

struct NumberNames {
    cardinal: &'static str,
    ordinal: &'static str,
}

impl NumberNames {
    fn get_name(&self, ordinal: bool) -> &'static str {
        if ordinal {
            return self.ordinal;
        }
        self.cardinal
    }
}

const SMALL_NAMES: [NumberNames; 20] = [
    NumberNames {
        cardinal: "zero",
        ordinal: "zeroth",
    },
    NumberNames {
        cardinal: "one",
        ordinal: "first",
    },
    NumberNames {
        cardinal: "two",
        ordinal: "second",
    },
    NumberNames {
        cardinal: "three",
        ordinal: "third",
    },
    NumberNames {
        cardinal: "four",
        ordinal: "fourth",
    },
    NumberNames {
        cardinal: "five",
        ordinal: "fifth",
    },
    NumberNames {
        cardinal: "six",
        ordinal: "sixth",
    },
    NumberNames {
        cardinal: "seven",
        ordinal: "seventh",
    },
    NumberNames {
        cardinal: "eight",
        ordinal: "eighth",
    },
    NumberNames {
        cardinal: "nine",
        ordinal: "ninth",
    },
    NumberNames {
        cardinal: "ten",
        ordinal: "tenth",
    },
    NumberNames {
        cardinal: "eleven",
        ordinal: "eleventh",
    },
    NumberNames {
        cardinal: "twelve",
        ordinal: "twelfth",
    },
    NumberNames {
        cardinal: "thirteen",
        ordinal: "thirteenth",
    },
    NumberNames {
        cardinal: "fourteen",
        ordinal: "fourteenth",
    },
    NumberNames {
        cardinal: "fifteen",
        ordinal: "fifteenth",
    },
    NumberNames {
        cardinal: "sixteen",
        ordinal: "sixteenth",
    },
    NumberNames {
        cardinal: "seventeen",
        ordinal: "seventeenth",
    },
    NumberNames {
        cardinal: "eighteen",
        ordinal: "eighteenth",
    },
    NumberNames {
        cardinal: "nineteen",
        ordinal: "nineteenth",
    },
];

const TENS: [NumberNames; 8] = [
    NumberNames {
        cardinal: "twenty",
        ordinal: "twentieth",
    },
    NumberNames {
        cardinal: "thirty",
        ordinal: "thirtieth",
    },
    NumberNames {
        cardinal: "forty",
        ordinal: "fortieth",
    },
    NumberNames {
        cardinal: "fifty",
        ordinal: "fiftieth",
    },
    NumberNames {
        cardinal: "sixty",
        ordinal: "sixtieth",
    },
    NumberNames {
        cardinal: "seventy",
        ordinal: "seventieth",
    },
    NumberNames {
        cardinal: "eighty",
        ordinal: "eightieth",
    },
    NumberNames {
        cardinal: "ninety",
        ordinal: "ninetieth",
    },
];

struct NamedNumber {
    cardinal: &'static str,
    ordinal: &'static str,
    number: usize,
}

impl NamedNumber {
    fn get_name(&self, ordinal: bool) -> &'static str {
        if ordinal {
            return self.ordinal;
        }
        self.cardinal
    }
}

const N: usize = 7;
const NAMED_NUMBERS: [NamedNumber; N] = [
    NamedNumber {
        cardinal: "hundred",
        ordinal: "hundredth",
        number: 100,
    },
    NamedNumber {
        cardinal: "thousand",
        ordinal: "thousandth",
        number: 1000,
    },
    NamedNumber {
        cardinal: "million",
        ordinal: "millionth",
        number: 1000000,
    },
    NamedNumber {
        cardinal: "billion",
        ordinal: "billionth",
        number: 1000000000,
    },
    NamedNumber {
        cardinal: "trillion",
        ordinal: "trillionth",
        number: 1000000000000,
    },
    NamedNumber {
        cardinal: "quadrillion",
        ordinal: "quadrillionth",
        number: 1000000000000000,
    },
    NamedNumber {
        cardinal: "quintillion",
        ordinal: "quintillionth",
        number: 1000000000000000000,
    },
];

fn big_name(n: usize) -> &'static NamedNumber {
    for i in 1..N {
        if n < NAMED_NUMBERS[i].number {
            return &NAMED_NUMBERS[i - 1];
        }
    }
    &NAMED_NUMBERS[N - 1]
}

fn count_letters(s: &str) -> usize {
    let mut count = 0;
    for c in s.chars() {
        if c.is_alphabetic() {
            count += 1;
        }
    }
    count
}

struct WordList {
    words: Vec<(usize, usize)>,
    string: String,
}

impl WordList {
    fn new() -> WordList {
        WordList {
            words: Vec::new(),
            string: String::new(),
        }
    }
    fn append(&mut self, s: &str) {
        let offset = self.string.len();
        self.string.push_str(s);
        self.words.push((offset, offset + s.len()));
    }
    fn extend(&mut self, s: &str) {
        let len = self.words.len();
        let mut w = &mut self.words[len - 1];
        w.1 += s.len();
        self.string.push_str(s);
    }
    fn len(&self) -> usize {
        self.words.len()
    }
    fn sentence_length(&self) -> usize {
        let n = self.words.len();
        if n == 0 {
            return 0;
        }
        self.string.len() + n - 1
    }
    fn get_word(&self, index: usize) -> &str {
        let w = &self.words[index];
        &self.string[w.0..w.1]
    }
}

fn append_number_name(words: &mut WordList, n: usize, ordinal: bool) -> usize {
    let mut count = 0;
    if n < 20 {
        words.append(SMALL_NAMES[n].get_name(ordinal));
        count += 1;
    } else if n < 100 {
        if n % 10 == 0 {
            words.append(TENS[n / 10 - 2].get_name(ordinal));
        } else {
            words.append(TENS[n / 10 - 2].get_name(false));
            words.extend("-");
            words.extend(SMALL_NAMES[n % 10].get_name(ordinal));
        }
        count += 1;
    } else {
        let big = big_name(n);
        count += append_number_name(words, n / big.number, false);
        if n % big.number == 0 {
            words.append(big.get_name(ordinal));
            count += 1;
        } else {
            words.append(big.get_name(false));
            count += 1;
            count += append_number_name(words, n % big.number, ordinal);
        }
    }
    count
}

fn sentence(count: usize) -> WordList {
    let mut result = WordList::new();
    const WORDS: &'static [&'static str] = &[
        "Four",
        "is",
        "the",
        "number",
        "of",
        "letters",
        "in",
        "the",
        "first",
        "word",
        "of",
        "this",
        "sentence,",
    ];
    for s in WORDS {
        result.append(s);
    }
    let mut n = result.len();
    let mut i = 1;
    while count > n {
        let count = count_letters(result.get_word(i));
        n += append_number_name(&mut result, count, false);
        result.append("in");
        result.append("the");
        n += 2;
        n += append_number_name(&mut result, i + 1, true);
        result.extend(",");
        i += 1;
    }
    result
}

fn main() {
    let mut n = 201;
    let s = sentence(n);
    println!("Number of letters in first {} words in the sequence:", n);
    for i in 0..n {
        if i != 0 {
            if i % 25 == 0 {
                println!();
            } else {
                print!(" ");
            }
        }
        print!("{:2}", count_letters(s.get_word(i)));
    }
    println!();
    println!("Sentence length: {}", s.sentence_length());
    n = 1000;
    while n <= 10000000 {
        let s = sentence(n);
        let word = s.get_word(n - 1);
        print!(
            "The {}th word is '{}' and has {} letters. ",
            n,
            word,
            count_letters(word)
        );
        println!("Sentence length: {}", s.sentence_length());
        n *= 10;
    }
}


Fractal tree

#include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif

#define SIZE           800
#define SCALE          5
#define BRANCHES       14
#define ROTATION_SCALE 0.75
#define INITIAL_LENGTH 50

double rand_fl(){
  return (double)rand() / (double)RAND_MAX;
}

void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
               double directionx, double directiony, double size,
               double rotation, int depth) {
#ifdef WITH_CAIRO
  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
                                                               CAIRO_FORMAT_RGB24,
							       surface->w, surface->h,
							       surface->pitch );
  cairo_t *ct = cairo_create(surf);

  cairo_set_line_width(ct, 1);
  cairo_set_source_rgba(ct, 0,0,0,1);
  cairo_move_to(ct, (int)offsetx, (int)offsety);
  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
  cairo_stroke(ct);
#else
  sge_AALine(surface,
      (int)offsetx, (int)offsety,
      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),
      SDL_MapRGB(surface->format, 0, 0, 0));
#endif
  if (depth > 0){

    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(rotation) + directiony * sin(rotation),
        directionx * -sin(rotation) + directiony * cos(rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);

    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(-rotation) + directiony * sin(-rotation),
        directionx * -sin(-rotation) + directiony * cos(-rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
  }
}

void render(SDL_Surface * surface){
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
  draw_tree(surface,
      surface->w / 2.0,
      surface->h - 10.0,
      0.0, -1.0,
      INITIAL_LENGTH,
      PI / 8,
      BRANCHES);
  SDL_UpdateRect(surface, 0, 0, 0, 0);
}

int main(){
  SDL_Surface * screen;
  SDL_Event evt;

  SDL_Init(SDL_INIT_VIDEO);

  srand((unsigned)time(NULL));

  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);

  render(screen);
  while(1){
    if (SDL_PollEvent(&evt)){
      if(evt.type == SDL_QUIT) break;
    }
    SDL_Delay(1);
  }
  SDL_Quit();
  return 0;
}

extern crate piston;
extern crate graphics;
extern crate opengl_graphics;
extern crate glutin_window;

use piston::window::WindowSettings;
use piston::event_loop::{Events, EventSettings};
use piston::input::RenderEvent;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use graphics::{clear, line, Context};

const ANG: f64 = 20.0;
const COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];
const LINE_THICKNESS: f64 = 5.0;
const DEPTH: u32 = 11;

fn main() {
    let mut window: Window = WindowSettings::new("Fractal Tree", [1024, 768])
        .opengl(OpenGL::V3_2)
        .exit_on_esc(true)
        .build()
        .unwrap();
    let mut gl = GlGraphics::new(OpenGL::V3_2);

    let mut events = Events::new(EventSettings::new());
    while let Some(e) = events.next(&mut window) {
        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, g| {
                clear([1.0, 1.0, 1.0, 1.0], g);
                draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);
            });
        }
    }
}

fn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {
    let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;
    let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;
    line(
        COLOR,
        LINE_THICKNESS * depth as f64 * 0.2,
        [x1, y1, x2, y2],
        c.transform,
        g,
    );
    if depth > 0 {
        draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);
        draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);
    }
}


Frobenius numbers

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LIMIT 10000

unsigned int sieve(unsigned int n, unsigned int **list) {
    unsigned char *sieve = calloc(n+1, 1);
    unsigned int i, j, max = 0;
    for (i = 2; i*i <= n; i++)
        if (!sieve[i])
            for (j = i+i; j <= n; j += i)
                sieve[j] = 1;
    for (i = 2; i <= n; i++) max += !sieve[i];
    *list = malloc(max * sizeof(unsigned int));
    for (i = 0, j = 2; j <= n; j++)
        if (!sieve[j]) (*list)[i++] = j;
    free(sieve);
    return i;
}

unsigned int frob(unsigned const int *primes, unsigned int n) {
    return primes[n] * primes[n+1] - primes[n] - primes[n+1];
}

int main() {

    unsigned int *primes;
    unsigned int amount = sieve(sqrt(LIMIT)+1, &primes);
    unsigned int i;

    for (i=0; i<amount-1; i++) printf("%d\n", frob(primes, i));
    free(primes);

    return 0;
}

fn frobenius_numbers() -> impl std::iter::Iterator<Item = (usize, bool)> {
    let mut primes = primal::Primes::all();
    let mut prime = primes.next().unwrap();
    std::iter::from_fn(move || {
        if let Some(p) = primes.by_ref().next() {
            let fnum = prime * p - prime - p;
            prime = p;
            return Some((fnum, primal::is_prime(fnum as u64)));
        }
        None
    })
}

fn main() {
    let limit = 1000000;
    let mut count = 0;
    println!(
        "Frobenius numbers less than {} (asterisk marks primes):",
        limit
    );
    for (fnum, is_prime) in frobenius_numbers().take_while(|(x, _)| *x < limit) {
        count += 1;
        let c = if is_prime { '*' } else { ' ' };
        let s = if count % 10 == 0 { '\n' } else { ' ' };
        print!("{:6}{}{}", fnum, c, s);
    }
    println!();
}


Function definition

double multiply(double a, double b)
{
   return a * b;
}

fn multiply(a: i32, b: i32) -> i32 {
    a * b
}


Gauss-Jordan matrix inversion

fn main() {
    let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0],
                                vec![4.0, 1.0, 6.0],
                                vec![7.0, 8.0, 9.0]
                                ];
    let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0],
                                vec![-1.0, 2.0, -1.0],
                                vec![0.0, -1.0, 2.0]
                                ];

    let mut ref_a = &mut a;
    let rref_a = &mut ref_a;
    let mut ref_b = &mut b;
    let rref_b = &mut ref_b;

    println!("Matrix A:\n");
    print_matrix(rref_a);
    println!("\nInverse of Matrix A:\n");
    print_matrix(&mut matrix_inverse(rref_a));
    println!("\n\nMatrix B:\n");
    print_matrix(rref_b);
    println!("\nInverse of Matrix B:\n");
    print_matrix(&mut matrix_inverse(rref_b));
}

fn matrix_inverse(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>>{
    let len = matrix.len();
    let mut aug = zero_matrix(len, len * 2);
    for i in 0..len {
        for j in 0.. len {
            aug[i][j] = matrix[i][j];
        }
        aug[i][i + len] = 1.0;
    }

    gauss_jordan_general(&mut aug);

    let mut unaug = zero_matrix(len, len);
    for i in 0..len {
        for j in 0..len {
            unaug[i][j] = aug[i][j+len];
        }
    }
    unaug
}

fn gauss_jordan_general(matrix: &mut Vec<Vec<f64>>) {
    let mut lead = 0;
    let row_count = matrix.len();
    let col_count = matrix[0].len();

    for r in 0..row_count {
        if col_count <= lead {
            break;
        }
        let mut i = r;
        while matrix[i][lead] == 0.0 {
            i = i + 1;
            if row_count == i {
                i = r;
                lead = lead + 1;
                if col_count == lead {
                    break;
                }
            }
        }

        let temp = matrix[i].to_owned();
        matrix[i] = matrix[r].to_owned();
        matrix[r] = temp.to_owned();

        if matrix[r][lead] != 0.0 {
            let div = matrix[r][lead];
            for j in 0..col_count {
                matrix[r][j] = matrix[r][j] / div;
            }
        }

        for k in 0..row_count {
            if k != r {
                let mult = matrix[k][lead];
                for j in 0..col_count {
                    matrix[k][j] = matrix[k][j] - matrix[r][j] * mult;
                }
            }
        }
        lead = lead + 1;

    }

}

fn zero_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> {
    let mut matrix = Vec::with_capacity(cols);
    for _ in 0..rows {
        let mut col: Vec<f64> = Vec::with_capacity(rows);
        for _ in 0..cols {
            col.push(0.0);
        }
        matrix.push(col);
    }
    matrix
}

fn print_matrix(mat: &mut Vec<Vec<f64>>) {
    for row in 0..mat.len(){
        println!("{:?}", mat[row]);
    }
}


Generate Chess960 starting position

#include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>

char rank[9];

int pos[8];

void swap(int i,int j){
	int temp = pos[i];
	pos[i] = pos[j];
	pos[j] = temp;
}

void generateFirstRank(){
	 int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;

	 for(i=0;i<8;i++){
		 rank[i] = 'e';
		 pos[i] = i;
	 }

	 do{
		 kPos = rand()%8;
		 rPos1 = rand()%8;
		 rPos2 = rand()%8;
	 }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));

	 rank[pos[rPos1]] = 'R';
	 rank[pos[kPos]] = 'K';
	 rank[pos[rPos2]] = 'R';

	 swap(rPos1,7);
	 swap(rPos2,6);
	 swap(kPos,5);

	 do{
		 bPos1 = rand()%5;
		 bPos2 = rand()%5;
	 }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));

	 rank[pos[bPos1]] = 'B';
	 rank[pos[bPos2]] = 'B';

	 swap(bPos1,4);
	 swap(bPos2,3);

	 do{
		 qPos = rand()%3;
		 nPos1 = rand()%3;
	 }while(qPos==nPos1);

	 rank[pos[qPos]] = 'Q';
	 rank[pos[nPos1]] = 'N';

	 for(i=0;i<8;i++)
		 if(rank[i]=='e'){
			 rank[i] = 'N';
			 break;
		 }
}

void printRank(){
	int i;

	#ifdef _WIN32
		printf("%s\n",rank);
	#else
	{
		setlocale(LC_ALL,"");
		printf("\n");
		for(i=0;i<8;i++){
			if(rank[i]=='K')
				printf("%lc",(wint_t)9812);
			else if(rank[i]=='Q')
				printf("%lc",(wint_t)9813);
			else if(rank[i]=='R')
				printf("%lc",(wint_t)9814);
			else if(rank[i]=='B')
				printf("%lc",(wint_t)9815);
			if(rank[i]=='N')
				printf("%lc",(wint_t)9816);
		}
	}
	#endif
}

int main()
{
	int i;

	srand((unsigned)time(NULL));

	for(i=0;i<9;i++){
		generateFirstRank();
		printRank();
	}

	return 0;
}

use std::collections::BTreeSet;

struct Chess960 ( BTreeSet<String> );

impl Chess960 {
    fn invoke(&mut self, b: &str, e: &str) {
        if e.len() <= 1 {
            let s = b.to_string() + e;
            if Chess960::is_valid(&s) { self.0.insert(s); }
        } else {
            for (i, c) in e.char_indices() {
                let mut b = b.to_string();
                b.push(c);
                let mut e = e.to_string();
                e.remove(i);
                self.invoke(&b, &e);
            }
        }
    }

    fn is_valid(s: &str) -> bool {
        let k = s.find('K').unwrap();
        k > s.find('R').unwrap() && k < s.rfind('R').unwrap() && s.find('B').unwrap() % 2 != s.rfind('B').unwrap() % 2
    }
}

fn main() {
    let mut chess960 = Chess960(BTreeSet::new());
    chess960.invoke("", "KQRRNNBB");

    for (i, p) in chess960.0.iter().enumerate() {
        println!("{}: {}", i, p);
    }
}


Generate random chess position

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define TRUE 1
#define FALSE 0

typedef int bool;

char grid[8][8];

void placeKings() {
    int r1, r2, c1, c2;
    for (;;) {
        r1 = rand() % 8;
        c1 = rand() % 8;
        r2 = rand() % 8;
        c2 = rand() % 8;
        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
            grid[r1][c1] = 'K';
            grid[r2][c2] = 'k';
            return;
        }
    }
}

void placePieces(const char *pieces, bool isPawn) {
    int n, r, c;
    int numToPlace = rand() % strlen(pieces);
    for (n = 0; n < numToPlace; ++n) {
        do {
            r = rand() % 8;
            c = rand() % 8;
        }
        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
        grid[r][c] = pieces[n];
    }
}

void toFen() {
    char fen[80], ch;
    int r, c, countEmpty = 0, index = 0;
    for (r = 0; r < 8; ++r) {
        for (c = 0; c < 8; ++c) {
            ch = grid[r][c];
            printf("%2c ", ch == 0 ? '.' : ch);
            if (ch == 0) {
                countEmpty++;
            }
            else {
                if (countEmpty > 0) {
                    fen[index++] = countEmpty + 48;
                    countEmpty = 0;
                }
                fen[index++] = ch;
            }
        }
        if (countEmpty > 0) {
            fen[index++] = countEmpty + 48;
            countEmpty = 0;
        }
        fen[index++]= '/';
        printf("\n");
    }
    strcpy(fen + index, " w - - 0 1");
    printf("%s\n", fen);
}

char *createFen() {
    placeKings();
    placePieces("PPPPPPPP", TRUE);
    placePieces("pppppppp", TRUE);
    placePieces("RNBQBNR", FALSE);
    placePieces("rnbqbnr", FALSE);
    toFen();
}

int main() {
    srand(time(NULL));
    createFen();
    return 0;
}

use std::fmt::Write;

use rand::{Rng, distributions::{Distribution, Standard}};

const EMPTY: u8 = b'.';

#[derive(Clone, Debug)]
struct Board {
    grid: [[u8; 8]; 8],
}

impl Distribution<Board> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Board {
        let mut board = Board::empty();
        board.place_kings(rng);
        board.place_pieces(rng, b"PPPPPPPP", true);
        board.place_pieces(rng, b"pppppppp", true);
        board.place_pieces(rng, b"RNBQBNR", false);
        board.place_pieces(rng, b"rnbqbnr", false);
        board
    }
}

impl Board {
    fn empty() -> Self {
        Board { grid: [[EMPTY; 8]; 8] }
    }

    fn fen(&self) -> String {
        let mut fen = String::new();
        let mut count_empty = 0;
        for row in &self.grid {
            for &ch in row {
                print!("{} ", ch as char);
                if ch == EMPTY {
                    count_empty += 1;
                } else {
                    if count_empty > 0 {
                        write!(fen, "{}", count_empty).unwrap();
                        count_empty = 0;
                    }
                    fen.push(ch as char);
                }
            }
            if count_empty > 0 {
                write!(fen, "{}", count_empty).unwrap();
                count_empty = 0;
            }
            fen.push('/');
            println!();
        }
        fen.push_str(" w - - 0 1");
        fen
    }

    fn place_kings<R: Rng + ?Sized>(&mut self, rng: &mut R) {
        loop {
            let r1: i8 = rng.gen_range(0, 8);
            let c1: i8 = rng.gen_range(0, 8);
            let r2: i8 = rng.gen_range(0, 8);
            let c2: i8 = rng.gen_range(0, 8);
            if r1 != r2 && (r1 - r2).abs() > 1 && (c1 - c2).abs() > 1 {
                self.grid[r1 as usize][c1 as usize] = b'K';
                self.grid[r2 as usize][c2 as usize] = b'k';
                return;
            }
        }
    }

    fn place_pieces<R: Rng + ?Sized>(&mut self, rng: &mut R, pieces: &[u8], is_pawn: bool) {
        let num_to_place = rng.gen_range(0, pieces.len());
        for &piece in pieces.iter().take(num_to_place) {
            let mut r = rng.gen_range(0, 8);
            let mut c = rng.gen_range(0, 8);
            while self.grid[r][c] != EMPTY || (is_pawn && (r == 7 || r == 0)) {
                r = rng.gen_range(0, 8);
                c = rng.gen_range(0, 8);
            }
            self.grid[r][c] = piece;
        }
    }
}

fn main() {
    let b: Board = rand::random();
    println!("{}", b.fen());
}


Greedy algorithm for Egyptian fractions

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

typedef int64_t integer;

struct Pair {
    integer md;
    int tc;
};

integer mod(integer x, integer y) {
    return ((x % y) + y) % y;
}

integer gcd(integer a, integer b) {
    if (0 == a) return b;
    if (0 == b) return a;
    if (a == b) return a;
    if (a > b) return gcd(a - b, b);
    return gcd(a, b - a);
}

void write0(bool show, char *str) {
    if (show) {
        printf(str);
    }
}

void write1(bool show, char *format, integer a) {
    if (show) {
        printf(format, a);
    }
}

void write2(bool show, char *format, integer a, integer b) {
    if (show) {
        printf(format, a, b);
    }
}

struct Pair egyptian(integer x, integer y, bool show) {
    struct Pair ret;
    integer acc = 0;
    bool first = true;

    ret.tc = 0;
    ret.md = 0;

    write2(show, "Egyptian fraction for %lld/%lld: ", x, y);
    while (x > 0) {
        integer z = (y + x - 1) / x;
        if (z == 1) {
            acc++;
        } else {
            if (acc > 0) {
                write1(show, "%lld + ", acc);
                first = false;
                acc = 0;
                ret.tc++;
            } else if (first) {
                first = false;
            } else {
                write0(show, " + ");
            }
            if (z > ret.md) {
                ret.md = z;
            }
            write1(show, "1/%lld", z);
            ret.tc++;
        }
        x = mod(-y, x);
        y = y * z;
    }
    if (acc > 0) {
        write1(show, "%lld", acc);
        ret.tc++;
    }
    write0(show, "\n");

    return ret;
}

int main() {
    struct Pair p;
    integer nm = 0, dm = 0, dmn = 0, dmd = 0, den = 0;;
    int tm, i, j;

    egyptian(43, 48, true);
    egyptian(5, 121, true);
    egyptian(2014, 59, true);

    tm = 0;
    for (i = 1; i < 100; i++) {
        for (j = 1; j < 100; j++) {
            p = egyptian(i, j, false);
            if (p.tc > tm) {
                tm = p.tc;
                nm = i;
                dm = j;
            }
            if (p.md > den) {
                den = p.md;
                dmn = i;
                dmd = j;
            }
        }
    }
    printf("Term max is %lld/%lld with %d terms.\n", nm, dm, tm);
    printf("Denominator max is %lld/%lld\n", dmn, dmd);
    egyptian(dmn, dmd, true);

    return 0;
}

use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Zero};
use std::fmt;

#[derive(Debug, Clone, PartialEq, PartialOrd)]
struct Rational {
    nominator: BigInt,
    denominator: BigInt,
}

impl Rational {
    fn new(n: &BigInt, d: &BigInt) -> Rational {
        assert!(!d.is_zero(), "denominator cannot be 0");

        let c = n.gcd(d);
        Rational {
            nominator: n / &c,
            denominator: d / &c,
        }
    }

    fn is_proper(&self) -> bool {
        self.nominator < self.denominator
    }
    fn to_egyptian(&self) -> Vec<Rational> {
        let mut frac: Vec<Rational> = Vec::new();

        let mut current: Rational;
        if !self.is_proper() {

            frac.push(Rational::new(
                &self.nominator.div_floor(&self.denominator),
                &One::one(),
            ));

            current = Rational::new(
                &self.nominator.mod_floor(&self.denominator),
                &self.denominator,
            );
        } else {
            current = self.clone();
        }

        while !current.nominator.is_one() {
            let div = current.denominator.div_ceil(&current.nominator);

            frac.push(Rational::new(&One::one(), &div));

            current = Rational::new(
                &(-&current.denominator).mod_floor(&current.nominator),
                match current.denominator.checked_mul(&div).as_ref() {
                    Some(r) => r,
                    _ => break,
                },
            );
        }

        frac.push(current);
        frac
    }
}

impl fmt::Display for Rational {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.denominator.is_one() {

            write!(f, "{}", self.nominator)
        } else {
            write!(f, "{}/{}", self.nominator, self.denominator)
        }
    }
}

fn rational_vec_to_string(vec: Vec<Rational>) -> String {
    let mut p = vec
        .iter()
        .fold(String::new(), |acc, num| (acc + &num.to_string() + ", "));

    if p.len() > 1 {
        p.truncate(p.len() - 2);
    }
    format!("[{}]", p)
}

fn run_max_searches(x: usize) {

    let pairs = (1..x).flat_map(move |i| (i + 1..x).map(move |j| (i, j)));

    let mut max_length = (0, Rational::new(&BigInt::from(1), &BigInt::from(1)));
    let mut max_denom = (
        Zero::zero(),
        Rational::new(&BigInt::from(1), &BigInt::from(1)),
    );

    for (i, j) in pairs {
        let e = Rational::new(&BigInt::from(i), &BigInt::from(j)).to_egyptian();
        if e.len() > max_length.0 {
            max_length = (e.len(), Rational::new(&BigInt::from(i), &BigInt::from(j)));
        }

        if e.last().unwrap().denominator > max_denom.0 {
            max_denom = (
                e.last().unwrap().denominator.clone(),
                Rational::new(&BigInt::from(i), &BigInt::from(j)),
            );
        }
    }

    println!(
        "Maximum length of terms is for {} with {} terms",
        max_length.1, max_length.0
    );
    println!("{}", rational_vec_to_string(max_length.1.to_egyptian()));

    println!(
        "Maximum denominator is for {} with {} terms",
        max_denom.1, max_denom.0
    );
    println!("{}", rational_vec_to_string(max_denom.1.to_egyptian()));
}
fn main() {
    let tests = [
        Rational::new(&BigInt::from(43), &BigInt::from(48)),
        Rational::new(&BigInt::from(5), &BigInt::from(121)),
        Rational::new(&BigInt::from(2014), &BigInt::from(59)),
    ];

    for test in tests.iter() {
        println!("{} -> {}", test, rational_vec_to_string(test.to_egyptian()));
    }

    run_max_searches(100);
    run_max_searches(1000);
}


#include <stdio.h>
#include <stdlib.h>
#include "curl/curl.h"

int
main(void)
{
        CURL *curl;
        char buffer[CURL_ERROR_SIZE];

        if ((curl = curl_easy_init()) != NULL) {
                curl_easy_setopt(curl, CURLOPT_URL, "https:
                curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
                if (curl_easy_perform(curl) != CURLE_OK) {
                        fprintf(stderr, "%s\n", buffer);
                        return EXIT_FAILURE;
                }
                curl_easy_cleanup(curl);
        }
        return EXIT_SUCCESS;
}

extern crate reqwest;

use reqwest::blocking::Client;
use reqwest::header::CONNECTION;

fn main() {
    let client = Client::new();

    let res = client
        .get("https:
        .basic_auth("user", Some("password"))
        .header(CONNECTION, "close")
        .send()
        .unwrap();

    let body = res.text().unwrap();

    println!("{}", body);
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"

void C_curlAllocate(WrenVM* vm) {
    CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
    *pcurl = curl_easy_init();
}

void C_easyPerform(WrenVM* vm) {
    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
    CURLcode cc = curl_easy_perform(curl);
    wrenSetSlotDouble(vm, 0, (double)cc);
}

void C_easyCleanup(WrenVM* vm) {
    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
    curl_easy_cleanup(curl);
}

void C_easySetOpt(WrenVM* vm) {
    CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
    CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
    const char *arg = wrenGetSlotString(vm, 2);
    curl_easy_setopt(curl, opt, arg);
}

WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
    WrenForeignClassMethods methods;
    methods.allocate = NULL;
    methods.finalize = NULL;
    if (strcmp(module, "main") == 0) {
        if (strcmp(className, "Curl") == 0) {
            methods.allocate = C_curlAllocate;
        }
    }
    return methods;
}

WrenForeignMethodFn bindForeignMethod(
    WrenVM* vm,
    const char* module,
    const char* className,
    bool isStatic,
    const char* signature) {
    if (strcmp(module, "main") == 0) {
        if (strcmp(className, "Curl") == 0) {
            if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
            if (!isStatic && strcmp(signature, "easyPerform()") == 0)   return C_easyPerform;
            if (!isStatic && strcmp(signature, "easyCleanup()") == 0)   return C_easyCleanup;
        }
    }
    return NULL;
}

static void writeFn(WrenVM* vm, const char* text) {
    printf("%s", text);
}

void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
    switch (errorType) {
        case WREN_ERROR_COMPILE:
            printf("[%s line %d] [Error] %s\n", module, line, msg);
            break;
        case WREN_ERROR_STACK_TRACE:
            printf("[%s line %d] in %s\n", module, line, msg);
            break;
        case WREN_ERROR_RUNTIME:
            printf("[Runtime Error] %s\n", msg);
            break;
    }
}

char *readFile(const char *fileName) {
    FILE *f = fopen(fileName, "r");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    rewind(f);
    char *script = malloc(fsize + 1);
    fread(script, 1, fsize, f);
    fclose(f);
    script[fsize] = 0;
    return script;
}

int main(int argc, char **argv) {
    WrenConfiguration config;
    wrenInitConfiguration(&config);
    config.writeFn = &writeFn;
    config.errorFn = &errorFn;
    config.bindForeignClassFn = &bindForeignClass;
    config.bindForeignMethodFn = &bindForeignMethod;
    WrenVM* vm = wrenNewVM(&config);
    const char* module = "main";
    const char* fileName = "https_client-authenticated.wren";
    char *script = readFile(fileName);
    WrenInterpretResult result = wrenInterpret(vm, module, script);
    switch (result) {
        case WREN_RESULT_COMPILE_ERROR:
            printf("Compile Error!\n");
            break;
        case WREN_RESULT_RUNTIME_ERROR:
            printf("Runtime Error!\n");
            break;
        case WREN_RESULT_SUCCESS:
            break;
    }
    wrenFreeVM(vm);
    free(script);
    return 0;
}

use std::fs::File;
use std::io::Read;

use reqwest::blocking::Client;
use reqwest::Identity;

fn main() -> std::io::Result<()> {
    let identity = {
        let mut buf = Vec::new();

        File::open("badssl.com-client.p12")?.read_to_end(&mut buf)?;

        Identity::from_pkcs12_der(&buf, "badssl.com").unwrap()
    };

    let client = Client::builder().identity(identity).build().unwrap();
    let response = client.get("https:

    if !response.status().is_success() {
        eprintln!("HTTP error requesting URL: {}", response.status());
    }

    println!("Got response from server: {}", response.text().unwrap());

    Ok(())
}


Honaker primes

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>

#define LIMIT 5000000

typedef struct {
    int x;
    int y;
} pair;

int *primeSieve(int limit, int *length) {
    int i, p, *primes;
    int j, pc = 0;
    limit++;

    bool *c = calloc(limit, sizeof(bool));
    c[0] = true;
    c[1] = true;
    for (i = 4; i < limit; i += 2) c[i] = true;
    p = 3;
    while (true) {
        int p2 = p * p;
        if (p2 >= limit) break;
        for (i = p2; i < limit; i += 2 * p) c[i] = true;
        while (true) {
            p += 2;
            if (!c[p]) break;
        }
    }
    for (i = 0; i < limit; ++i) {
        if (!c[i]) ++pc;
    }
    primes = (int *)malloc(pc * sizeof(int));
    for (i = 0, j = 0; i < limit; ++i) {
        if (!c[i]) primes[j++] = i;
    }
    free(c);
    *length = pc;
    return primes;
}

int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int i, count, length, hc = 0;
    int *primes = (int *)primeSieve(LIMIT, &length);
    pair h[50], h10000;
    for (i = 1, count = 0; count < 10000; ++i) {
        if (digitSum(i) == digitSum(primes[i-1])) {
            ++count;
            if (count <= 50) {
                h[hc++] = (pair){i, primes[i-1]};
            } else if (count == 10000) {
                h10000.x = i;
                h10000.y = primes[i-1];
            }
        }
    }
    setlocale(LC_NUMERIC, "");
    printf("The first 50 Honaker primes (index, prime):\n");
    for (i = 0; i < 50; ++i) {
        printf("(%3d, %'5d) ", h[i].x, h[i].y);
        if (!((i+1)%5)) printf("\n");
    }
    printf("\nand the 10,000th: (%'7d, %'9d)\n", h10000.x, h10000.y);
    free(primes);
    return 0;
}

fn digit_sum( mut number: usize) -> usize {
   let mut sum : usize = 0 ;
   while number != 0 {
      sum += number % 10 ;
      number /= 10 ;
   }
   sum
}

fn main() {
   let mut count : i32 = 0 ;
   let mut pos : i32 = 1 ;
   println!("The first 50 Honaker primes:") ;
   primal::Primes::all( ).enumerate( ).map( |( i , w )| (i + 1 , w) ).
      filter( |(i , w)| digit_sum( *i ) == digit_sum( *w ) ).take( 50 ).
      for_each( |(i , w )| {
            count += 1 ;
            print!("(p:{} ,ind:{} ,val:{}) " , pos , i, w ) ;
            pos += 1 ;
            if count % 3 == 0 {
               println!( ) ;
            }
      }) ;
   println!( ) ;
}


Hough transform

#include "SL_Generated.h"
#include "CImg.h"

using namespace cimg_library;

int main( int argc, char** argv )
{
    string fileName = "Pentagon.bmp";
    if(argc > 1) fileName = argv[1];
    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);
    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);
    int threads = 0; if(argc > 5) threads = atoi(argv[5]);
    char titleBuffer[200];
    SLTimer t;

    CImg<int> image(fileName.c_str());
    int imageDimensions[] = {image.height(), image.width(), 0};
    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);
    Sequence< Sequence<int> > result;

    sl_init(threads);

    t.start();
    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);
    t.stop();

    CImg<int> resultImage(result[1].size(), result.size());
    for(int y = 0; y < result.size(); y++)
        for(int x = 0; x < result[y+1].size(); x++)
            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];

    sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0",
                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());
    resultImage.display(titleBuffer);

    sl_done();
    return 0;
}

use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
use std::iter::repeat;

struct ImageGray8 {
    width: usize,
    height: usize,
    data: Vec<u8>,
}

fn load_pgm(filename: &str) -> io::Result<ImageGray8> {

    let mut file = BufReader::new(File::open(filename)?);

    let mut magic_in = String::new();
    let _ = file.read_line(&mut magic_in)?;
    let mut width_in = String::new();
    let _ = file.read_line(&mut width_in)?;
    let mut height_in = String::new();
    let _ = file.read_line(&mut height_in)?;
    let mut maxval_in = String::new();
    let _ = file.read_line(&mut maxval_in)?;

    assert_eq!(magic_in, "P5\n");
    assert_eq!(maxval_in, "255\n");

    let width = width_in
        .trim()
        .parse::<usize>()
        .map_err(|_| io::ErrorKind::InvalidData)?;
    let height: usize = height_in
        .trim()
        .parse::<usize>()
        .map_err(|_| io::ErrorKind::InvalidData)?;

    println!("Reading pgm file {}: {} x {}", filename, width, height);

    let mut img = ImageGray8 {
        width,
        height,
        data: vec![],
    };

    let expected_bytes = width * height;
    let bytes_read = file.read_to_end(&mut img.data)?;
    if bytes_read != expected_bytes {
        let kind = if bytes_read < expected_bytes {
            io::ErrorKind::UnexpectedEof
        } else {
            io::ErrorKind::InvalidData
        };
        let msg = format!("expected {} bytes", expected_bytes);
        return Err(io::Error::new(kind, msg));
    }

    Ok(img)
}

fn save_pgm(img: &ImageGray8, filename: &str) {

    let mut file = BufWriter::new(File::create(filename).unwrap());

    if let Err(e) = writeln!(&mut file, "P5\n{}\n{}\n255", img.width, img.height) {
        println!("Failed to write header: {}", e);
    }

    println!(
        "Writing pgm file {}: {} x {}",
        filename, img.width, img.height
    );

    if let Err(e) = file.write_all(&(img.data[..])) {
        println!("Failed to image data: {}", e);
    }
}

#[allow(clippy::cast_precision_loss)]
#[allow(clippy::clippy::cast_possible_truncation)]
fn hough(image: &ImageGray8, out_width: usize, out_height: usize) -> ImageGray8 {
    let in_width = image.width;
    let in_height = image.height;

    let out_height = ((out_height / 2) * 2) as usize;
    let mut accum = ImageGray8 {
        width: out_width,
        height: out_height,
        data: repeat(255).take(out_width * out_height).collect(),
    };

    let rmax = (in_width as f64).hypot(in_height as f64);
    let dr = rmax / (out_height / 2) as f64;
    let dth = std::f64::consts::PI / out_width as f64;

    for y in 0..in_height {
        for x in 0..in_width {
            let in_idx = y * in_width + x;
            let col = image.data[in_idx];
            if col == 255 {
                continue;
            }

            for jtx in 0..out_width {
                let th = dth * (jtx as f64);
                let r = (x as f64) * (th.cos()) + (y as f64) * (th.sin());

                let iry = out_height as i64 / 2 - (r / (dr as f64) + 0.5).floor() as i64;
                #[allow(clippy::clippy::cast_sign_loss)]
                let out_idx = (jtx as i64 + iry * out_width as i64) as usize;
                let col = accum.data[out_idx];
                if col > 0 {
                    accum.data[out_idx] = col - 1;
                }
            }
        }
    }
    accum
}

fn main() -> io::Result<()> {
    let image = load_pgm("resources/Pentagon.pgm")?;
    let accum = hough(&image, 460, 360);
    save_pgm(&accum, "hough.pgm");
    Ok(())
}


I before E except after C

%{

  int cie, cei, ie, ei;
%}

%%

cie ++cie, ++ie;
cei ++cei, ++ei;
ie ++ie;
ei ++ei;
.|\n ;

%%

int main() {
  cie = cei = ie = ei = 0;
  yylex();
  printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible"));
  printf("%s: %s\n","E before I when preceded by C", (2*cie < cei ? "plausible" : "implausible"));
  printf("%s: %s\n","Overall, the rule is", (2*(cie+ei) < (cei+ie) ? "plausible" : "implausible"));
  return 0;
}

use std::default::Default;
use std::ops::AddAssign;

use itertools::Itertools;
use reqwest::get;

#[derive(Default, Debug)]
struct Feature<T> {
    pub cie: T,
    pub xie: T,
    pub cei: T,
    pub xei: T,
}

impl AddAssign<Feature<bool>> for Feature<u64> {
    fn add_assign(&mut self, rhs: Feature<bool>) {
        self.cei += rhs.cei as u64;
        self.xei += rhs.xei as u64;
        self.cie += rhs.cie as u64;
        self.xie += rhs.xie as u64;
    }
}

fn check_feature(word: &str) -> Feature<bool> {
    let mut feature: Feature<bool> = Default::default();

    for window in word.chars().tuple_windows::<(char, char, char)>() {
        match window {
            ('c', 'e', 'i') => { feature.cei = true }
            ('c', 'i', 'e') => { feature.cie = true }
            (not_c, 'e', 'i') if not_c != 'c' => (feature.xei = true),
            (not_c, 'i', 'e') if not_c != 'c' => (feature.xie = true),
            _ => {}
        }
    }

    feature
}

fn maybe_is_feature_plausible(feature_count: u64, opposing_count: u64) -> Option<bool> {
    if feature_count > 2 * opposing_count { Some(true) } else if opposing_count > 2 * feature_count { Some(false) } else { None }
}

fn print_feature_plausibility(feature_plausibility: Option<bool>, feature_name: &str) {
    let plausible_msg =
        match feature_plausibility {
            None => " is implausible",
            Some(true) => "is plausible",
            Some(false) => "is definitely implausible",
        };

    println!("{} {}", feature_name, plausible_msg)
}

fn main() {
    let mut res = get(" http:
    let texts = res.text().unwrap();

    let mut feature_count: Feature<u64> = Default::default();
    for word in texts.lines() {
        let feature = check_feature(word);
        feature_count += feature;
    }

    println!("Counting {:#?}", feature_count);

    let xie_plausibility =
        maybe_is_feature_plausible(feature_count.xie, feature_count.cie);
    let cei_plausibility =
        maybe_is_feature_plausible(feature_count.cei, feature_count.xei);

    print_feature_plausibility(xie_plausibility, "I before E when not preceded by C");
    print_feature_plausibility(cei_plausibility, "E before I when preceded by C");
    println!("The rule in general is {}",
             if xie_plausibility.unwrap_or(false) && cei_plausibility.unwrap_or(false)
             { "Plausible" } else { "Implausible" }
    );
}


Idiomatically determine all the lowercase and uppercase letters

#include <stdio.h>

int main(int argc, char const *argv[]) {
  for (char c = 0x41; c < 0x5b; c ++) putchar(c);
  putchar('\n');
  for (char c = 0x61; c < 0x7b; c ++) putchar(c);
  putchar('\n');
  return 0;
}

fn main() {
    println!(
        "Lowercase letters: {}",
        (b'a'..=b'z').map(|c| c as char).collect::<String>()
    );
    println!(
        "Uppercase letters: {}",
        (b'A'..=b'Z').map(|c| c as char).collect::<String>()
    );
}


Increasing gaps between consecutive Niven numbers

#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

uint64_t digit_sum(uint64_t n, uint64_t sum) {
    ++sum;
    while (n > 0 && n % 10 == 0) {
        sum -= 9;
        n /= 10;
    }
    return sum;
}

inline bool divisible(uint64_t n, uint64_t d) {
    if ((d & 1) == 0 && (n & 1) == 1)
        return false;
    return n % d == 0;
}

int main() {
    setlocale(LC_ALL, "");

    uint64_t previous = 1, gap = 0, sum = 0;
    int niven_index = 0, gap_index = 1;

    printf("Gap index  Gap    Niven index    Niven number\n");
    for (uint64_t niven = 1; gap_index <= 32; ++niven) {
        sum = digit_sum(niven, sum);
        if (divisible(niven, sum)) {
            if (niven > previous + gap) {
                gap = niven - previous;
                printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
                       gap, niven_index, previous);
            }
            previous = niven;
            ++niven_index;
        }
    }
    return 0;
}

fn digit_sum(mut n: u64, mut sum: u64) -> u64 {
    sum += 1;
    while n > 0 && n % 10 == 0 {
        sum -= 9;
        n /= 10;
    }
    sum
}

fn divisible(n: u64, d: u64) -> bool {
    if (d & 1) == 0 && (n & 1) == 1 {
        return false;
    }
    n % d == 0
}

fn main() {
    use num_format::{Locale, ToFormattedString};
    let mut previous = 1;
    let mut gap = 0;
    let mut sum = 0;
    let mut niven_index = 0;
    let mut gap_index = 1;
    let mut niven = 1;
    println!("Gap index  Gap    Niven index    Niven number");
    while gap_index <= 32 {
        sum = digit_sum(niven, sum);
        if divisible(niven, sum) {
            if niven > previous + gap {
                gap = niven - previous;
                println!(
                    "{:9} {:4} {:>14} {:>15}",
                    gap_index,
                    gap,
                    niven_index.to_formatted_string(&Locale::en),
                    previous.to_formatted_string(&Locale::en)
                );
                gap_index += 1;
            }
            previous = niven;
            niven_index += 1;
        }
        niven += 1;
    }
}


Integer roots

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

typedef unsigned long long ulong;

ulong root(ulong base, ulong n) {
    ulong n1, n2, n3, c, d, e;

    if (base < 2) return base;
    if (n == 0) return 1;

    n1 = n - 1;
    n2 = n;
    n3 = n1;
    c = 1;
    d = (n3 + base) / n2;
    e = (n3 * d + base / (ulong)powl(d, n1)) / n2;

    while (c != d && c != e) {
        c = d;
        d = e;
        e = (n3*e + base / (ulong)powl(e, n1)) / n2;
    }

    if (d < e) return d;
    return e;
}

int main() {
    ulong b = (ulong)2e18;

    printf("3rd root of 8 = %lld\n", root(8, 3));
    printf("3rd root of 9 = %lld\n", root(9, 3));
    printf("2nd root of %lld = %lld\n", b, root(b, 2));

    return 0;
}

fn shorten(s: &str, digits: usize) -> String {
    if s.len() <= digits + 3 {
        return String::from(s);
    }
    format!("{}...{}", &s[0..digits/2], &s[s.len()-digits/2..])
}

fn main() {
    use rug::{ops::Pow, Integer};

    let x = Integer::from(8);
    let r = Integer::from(x.root_ref(3));
    println!("Integer cube root of {}: {}", x, r);

    let x = Integer::from(9);
    let r = Integer::from(x.root_ref(3));
    println!("Integer cube root of {}: {}", x, r);

    let mut x = Integer::from(100).pow(2000);
    x *= 2;
    let s = Integer::from(x.root(2)).to_string();
    println!("First {} digits of the square root of 2:\n{}", s.len(), shorten(&s, 70));

    let mut x = Integer::from(100).pow(3000);
    x *= 2;
    let s = Integer::from(x.root(3)).to_string();
    println!("First {} digits of the cube root of 2:\n{}", s.len(), shorten(&s, 70));
}


Jacobi symbol

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

#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

int jacobi(unsigned long a, unsigned long n) {
	if (a >= n) a %= n;
	int result = 1;
	while (a) {
		while ((a & 1) == 0) {
			a >>= 1;
			if ((n & 7) == 3 || (n & 7) == 5) result = -result;
		}
		SWAP(a, n);
		if ((a & 3) == 3 && (n & 3) == 3) result = -result;
		a %= n;
	}
	if (n == 1) return result;
	return 0;
}

void print_table(unsigned kmax, unsigned nmax) {
	printf("n\\k|");
	for (int k = 0; k <= kmax; ++k) printf("%'3u", k);
	printf("\n----");
	for (int k = 0; k <= kmax; ++k) printf("---");
	putchar('\n');
	for (int n = 1; n <= nmax; n += 2) {
		printf("%-2u |", n);
		for (int k = 0; k <= kmax; ++k)
			printf("%'3d", jacobi(k, n));
		putchar('\n');
	}
}

int main() {
	print_table(20, 21);
	return 0;
}


Jacobsthal numbers

#include <stdio.h>
#include <gmp.h>

void jacobsthal(mpz_t r, unsigned long n) {
    mpz_t s;
    mpz_init(s);
    mpz_set_ui(r, 1);
    mpz_mul_2exp(r, r, n);
    mpz_set_ui(s, 1);
    if (n % 2) mpz_neg(s, s);
    mpz_sub(r, r, s);
    mpz_div_ui(r, r, 3);
}

void jacobsthal_lucas(mpz_t r, unsigned long n) {
    mpz_t a;
    mpz_init(a);
    mpz_set_ui(r, 1);
    mpz_mul_2exp(r, r, n);
    mpz_set_ui(a, 1);
    if (n % 2) mpz_neg(a, a);
    mpz_add(r, r, a);
}

int main() {
    int i, count;
    mpz_t jac[30], j;
    printf("First 30 Jacobsthal numbers:\n");
    for (i = 0; i < 30; ++i) {
        mpz_init(jac[i]);
        jacobsthal(jac[i], i);
        gmp_printf("%9Zd ", jac[i]);
        if (!((i+1)%5)) printf("\n");
    }

    printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
    mpz_init(j);
    for (i = 0; i < 30; ++i) {
        jacobsthal_lucas(j, i);
        gmp_printf("%9Zd ", j);
        if (!((i+1)%5)) printf("\n");
    }

    printf("\nFirst 20 Jacobsthal oblong numbers:\n");
    for (i = 0; i < 20; ++i) {
        mpz_mul(j, jac[i], jac[i+1]);
        gmp_printf("%11Zd ", j);
        if (!((i+1)%5)) printf("\n");
    }

    printf("\nFirst 20 Jacobsthal primes:\n");
    for (i = 0, count = 0; count < 20; ++i) {
        jacobsthal(j, i);
        if (mpz_probab_prime_p(j, 15) > 0) {
            gmp_printf("%Zd\n", j);
            ++count;
        }
    }

    return 0;
}

use rug::integer::IsPrime;
use rug::Integer;

fn jacobsthal_numbers() -> impl std::iter::Iterator<Item = Integer> {
    (0..).map(|x| ((Integer::from(1) << x) - if x % 2 == 0 { 1 } else { -1 }) / 3)
}

fn jacobsthal_lucas_numbers() -> impl std::iter::Iterator<Item = Integer> {
    (0..).map(|x| (Integer::from(1) << x) + if x % 2 == 0 { 1 } else { -1 })
}

fn jacobsthal_oblong_numbers() -> impl std::iter::Iterator<Item = Integer> {
    let mut jn = jacobsthal_numbers();
    let mut n0 = jn.next().unwrap();
    std::iter::from_fn(move || {
        let n1 = jn.next().unwrap();
        let result = Integer::from(&n0 * &n1);
        n0 = n1;
        Some(result)
    })
}

fn jacobsthal_primes() -> impl std::iter::Iterator<Item = Integer> {
    jacobsthal_numbers().filter(|x| x.is_probably_prime(30) != IsPrime::No)
}

fn main() {
    println!("First 30 Jacobsthal Numbers:");
    for (i, n) in jacobsthal_numbers().take(30).enumerate() {
        print!("{:9}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
    }
    println!("\nFirst 30 Jacobsthal-Lucas Numbers:");
    for (i, n) in jacobsthal_lucas_numbers().take(30).enumerate() {
        print!("{:9}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
    }
    println!("\nFirst 20 Jacobsthal oblong Numbers:");
    for (i, n) in jacobsthal_oblong_numbers().take(20).enumerate() {
        print!("{:11}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
    }
    println!("\nFirst 20 Jacobsthal primes:");
    for n in jacobsthal_primes().take(20) {
        println!("{}", n);
    }
}


Jaro similarity

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

#define TRUE    1
#define FALSE   0

#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))

double jaro(const char *str1, const char *str2) {

    int str1_len = strlen(str1);
    int str2_len = strlen(str2);

    if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;

    int match_distance = (int) max(str1_len, str2_len)/2 - 1;

    int *str1_matches = calloc(str1_len, sizeof(int));
    int *str2_matches = calloc(str2_len, sizeof(int));

    double matches = 0.0;
    double transpositions = 0.0;

    for (int i = 0; i < str1_len; i++) {

        int start = max(0, i - match_distance);
        int end = min(i + match_distance + 1, str2_len);

        for (int k = start; k < end; k++) {

            if (str2_matches[k]) continue;

            if (str1[i] != str2[k]) continue;

            str1_matches[i] = TRUE;
            str2_matches[k] = TRUE;
            matches++;
            break;
        }
    }

    if (matches == 0) {
        free(str1_matches);
        free(str2_matches);
        return 0.0;
    }

    int k = 0;
    for (int i = 0; i < str1_len; i++) {

        if (!str1_matches[i]) continue;

        while (!str2_matches[k]) k++;

        if (str1[i] != str2[k]) transpositions++;
        k++;
    }

    transpositions /= 2.0;

    free(str1_matches);
    free(str2_matches);

    return ((matches / str1_len) +
        (matches / str2_len) +
        ((matches - transpositions) / matches)) / 3.0;
}

int main() {
    printf("%f\n", jaro("MARTHA",    "MARHTA"));
    printf("%f\n", jaro("DIXON",     "DICKSONX"));
    printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"));
}

use std::cmp;

pub fn jaro(s1: &str, s2: &str) -> f64 {
    let s1_len = s1.len();
    let s2_len = s2.len();
    if s1_len == 0 && s2_len == 0 { return 1.0; }
    let match_distance = cmp::max(s1_len, s2_len) / 2 - 1;
    let mut s1_matches = vec![false; s1_len];
    let mut s2_matches = vec![false; s2_len];
    let mut m: isize = 0;
    for i in 0..s1_len {
        let start = cmp::max(0, i as isize - match_distance as isize) as usize;
        let end = cmp::min(i + match_distance + 1, s2_len);
        for j in start..end {
            if !s2_matches[j] && s1.as_bytes()[i] == s2.as_bytes()[j] {
                s1_matches[i] = true;
                s2_matches[j] = true;
                m += 1;
                break;
            }
        }
    }
    if m == 0 { return 0.0; }
    let mut t = 0.0;
    let mut k = 0;
    for i in 0..s1_len {
        if s1_matches[i] {
            while !s2_matches[k] { k += 1; }
            if s1.as_bytes()[i] != s2.as_bytes()[k] { t += 0.5; }
            k += 1;
        }
    }

    let m = m as f64;
    (m / s1_len as f64 + m / s2_len as f64 + (m  - t) / m) / 3.0
}

fn main() {
    let pairs = [("MARTHA", "MARHTA"), ("DIXON", "DICKSONX"), ("JELLYFISH", "SMELLYFISH")];
    for p in pairs.iter() { println!("{}/{} = {}", p.0, p.1, jaro(p.0, p.1)); }
}


K-d tree

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

#define MAX_DIM 3
struct kd_node_t{
    double x[MAX_DIM];
    struct kd_node_t *left, *right;
};

    inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
    double t, d = 0;
    while (dim--) {
        t = a->x[dim] - b->x[dim];
        d += t * t;
    }
    return d;
}
inline void swap(struct kd_node_t *x, struct kd_node_t *y) {
    double tmp[MAX_DIM];
    memcpy(tmp,  x->x, sizeof(tmp));
    memcpy(x->x, y->x, sizeof(tmp));
    memcpy(y->x, tmp,  sizeof(tmp));
}

    struct kd_node_t*
find_median(struct kd_node_t *start, struct kd_node_t *end, int idx)
{
    if (end <= start) return NULL;
    if (end == start + 1)
        return start;

    struct kd_node_t *p, *store, *md = start + (end - start) / 2;
    double pivot;
    while (1) {
        pivot = md->x[idx];

        swap(md, end - 1);
        for (store = p = start; p < end; p++) {
            if (p->x[idx] < pivot) {
                if (p != store)
                    swap(p, store);
                store++;
            }
        }
        swap(store, end - 1);

        if (store->x[idx] == md->x[idx])
            return md;

        if (store > md) end = store;
        else        start = store;
    }
}

    struct kd_node_t*
make_tree(struct kd_node_t *t, int len, int i, int dim)
{
    struct kd_node_t *n;

    if (!len) return 0;

    if ((n = find_median(t, t + len, i))) {
        i = (i + 1) % dim;
        n->left  = make_tree(t, n - t, i, dim);
        n->right = make_tree(n + 1, t + len - (n + 1), i, dim);
    }
    return n;
}

int visited;

void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,
        struct kd_node_t **best, double *best_dist)
{
    double d, dx, dx2;

    if (!root) return;
    d = dist(root, nd, dim);
    dx = root->x[i] - nd->x[i];
    dx2 = dx * dx;

    visited ++;

    if (!*best || d < *best_dist) {
        *best_dist = d;
        *best = root;
    }

    if (!*best_dist) return;

    if (++i >= dim) i = 0;

    nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);
    if (dx2 >= *best_dist) return;
    nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);
}

#define N 1000000
#define rand1() (rand() / (double)RAND_MAX)
#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }
int main(void)
{
    int i;
    struct kd_node_t wp[] = {
        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
    };
    struct kd_node_t testNode = {{9, 2}};
    struct kd_node_t *root, *found, *million;
    double best_dist;

    root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);

    visited = 0;
    found = 0;
    nearest(root, &testNode, 0, 2, &found, &best_dist);

    printf(">> WP tree\nsearching for (%g, %g)\n"
            "found (%g, %g) dist %g\nseen %d nodes\n\n",
            testNode.x[0], testNode.x[1],
            found->x[0], found->x[1], sqrt(best_dist), visited);

    million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));
    srand(time(0));
    for (i = 0; i < N; i++) rand_pt(million[i]);

    root = make_tree(million, N, 0, 3);
    rand_pt(testNode);

    visited = 0;
    found = 0;
    nearest(root, &testNode, 0, 3, &found, &best_dist);

    printf(">> Million tree\nsearching for (%g, %g, %g)\n"
            "found (%g, %g, %g) dist %g\nseen %d nodes\n",
            testNode.x[0], testNode.x[1], testNode.x[2],
            found->x[0], found->x[1], found->x[2],
            sqrt(best_dist), visited);

    int sum = 0, test_runs = 100000;
    for (i = 0; i < test_runs; i++) {
        found = 0;
        visited = 0;
        rand_pt(testNode);
        nearest(root, &testNode, 0, 3, &found, &best_dist);
        sum += visited;
    }
    printf("\n>> Million tree\n"
            "visited %d nodes for %d random findings (%f per lookup)\n",
            sum, test_runs, sum/(double)test_runs);

    return 0;
}

use std::cmp::Ordering;
use std::cmp::Ordering::Less;
use std::ops::Sub;
use std::time::Instant;

use rand::prelude::*;

#[derive(Clone, PartialEq, Debug)]
struct Point {
    pub coords: Vec<f32>,
}

impl<'a, 'b> Sub<&'b Point> for &'a Point {
    type Output = Point;

    fn sub(self, rhs: &Point) -> Point {
        assert_eq!(self.coords.len(), rhs.coords.len());
        Point {
            coords: self
                .coords
                .iter()
                .zip(rhs.coords.iter())
                .map(|(&x, &y)| x - y)
                .collect(),
        }
    }
}

impl Point {
    fn norm_sq(&self) -> f32 {
        self.coords.iter().map(|n| n * n).sum()
    }
}

struct KDTreeNode {
    point: Point,
    dim: usize,

    left: Option<Box<KDTreeNode>>,
    right: Option<Box<KDTreeNode>>,
}

impl KDTreeNode {

    pub fn new(points: &mut [Point], dim: usize) -> KDTreeNode {
        let points_len = points.len();
        if points_len == 1 {
            return KDTreeNode {
                point: points[0].clone(),
                dim,
                left: None,
                right: None,
            };
        }

        let pivot = quickselect_by(points, points_len / 2, &|a, b| {
            a.coords[dim].partial_cmp(&b.coords[dim]).unwrap()
        });

        let left = Some(Box::new(KDTreeNode::new(
            &mut points[0..points_len / 2],
            (dim + 1) % pivot.coords.len(),
        )));
        let right = if points.len() >= 3 {
            Some(Box::new(KDTreeNode::new(
                &mut points[points_len / 2 + 1..points_len],
                (dim + 1) % pivot.coords.len(),
            )))
        } else {
            None
        };

        KDTreeNode {
            point: pivot,
            dim,
            left,
            right,
        }
    }

    pub fn find_nearest_neighbor<'a>(&'a self, point: &Point) -> (&'a Point, usize) {
        self.find_nearest_neighbor_helper(point, &self.point, (point - &self.point).norm_sq(), 1)
    }

    fn find_nearest_neighbor_helper<'a>(
        &'a self,
        point: &Point,
        best: &'a Point,
        best_dist_sq: f32,
        n_visited: usize,
    ) -> (&'a Point, usize) {
        let mut my_best = best;
        let mut my_best_dist_sq = best_dist_sq;
        let mut my_n_visited = n_visited;

        if self.point.coords[self.dim] < point.coords[self.dim] && self.right.is_some() {
            let (a, b) = self.right.as_ref().unwrap().find_nearest_neighbor_helper(
                point,
                my_best,
                my_best_dist_sq,
                my_n_visited,
            );
            my_best = a;
            my_n_visited = b;
        } else if self.left.is_some() {
            let (a, b) = self.left.as_ref().unwrap().find_nearest_neighbor_helper(
                point,
                my_best,
                my_best_dist_sq,
                my_n_visited,
            );
            my_best = a;
            my_n_visited = b;
        }

        let axis_dist_sq = (self.point.coords[self.dim] - point.coords[self.dim]).powi(2);
        if axis_dist_sq <= my_best_dist_sq {

            let self_dist_sq = (point - &self.point).norm_sq();
            if self_dist_sq < my_best_dist_sq {
                my_best = &self.point;
                my_best_dist_sq = self_dist_sq;
            }

            my_n_visited += 1;

            if self.point.coords[self.dim] < point.coords[self.dim] && self.left.is_some() {
                let (a, b) = self.left.as_ref().unwrap().find_nearest_neighbor_helper(
                    point,
                    my_best,
                    my_best_dist_sq,
                    my_n_visited,
                );
                my_best = a;
                my_n_visited = b;
            } else if self.right.is_some() {
                let (a, b) = self.right.as_ref().unwrap().find_nearest_neighbor_helper(
                    point,
                    my_best,
                    my_best_dist_sq,
                    my_n_visited,
                );
                my_best = a;
                my_n_visited = b;
            }
        }

        (my_best, my_n_visited)
    }
}

pub fn main() {
    let mut rng = thread_rng();

    let mut wp_points: Vec<Point> = [
        [2.0, 3.0],
        [5.0, 4.0],
        [9.0, 6.0],
        [4.0, 7.0],
        [8.0, 1.0],
        [7.0, 2.0],
    ]
    .iter()
    .map(|x| Point { coords: x.to_vec() })
    .collect();
    let wp_tree = KDTreeNode::new(&mut wp_points, 0);

    let wp_target = Point {
        coords: vec![9.0, 2.0],
    };
    let (point, n_visited) = wp_tree.find_nearest_neighbor(&wp_target);
    println!("Wikipedia example data:");
    println!("Point: [9, 2]");
    println!("Nearest neighbor: {:?}", point);
    println!("Distance: {}", (point - &wp_target).norm_sq().sqrt());
    println!("Nodes visited: {}", n_visited);

    let n_random = 1000;
    let mut make_random_point = || Point {
        coords: (0..3).map(|_| (rng.gen::<f32>() - 0.5) * 1000.0).collect(),
    };
    let mut random_points: Vec<Point> = (0..n_random).map(|_| make_random_point()).collect();

    let start_cons_time = Instant::now();
    let random_tree = KDTreeNode::new(&mut random_points, 0);
    let cons_time = start_cons_time.elapsed();
    println!(
        "1,000 3d points (Construction time: {}ms)",
        cons_time.as_millis(),
    );

    let random_target = make_random_point();

    let (point, n_visited) = random_tree.find_nearest_neighbor(&random_target);
    println!("Point: {:?}", random_target);
    println!("Nearest neighbor: {:?}", point);
    println!("Distance: {}", (point - &random_target).norm_sq().sqrt());
    println!("Nodes visited: {}", n_visited);

    let n_searches = 1000;
    let random_targets: Vec<Point> = (0..n_searches).map(|_| make_random_point()).collect();

    let start_search_time = Instant::now();
    let mut total_n_visited = 0;
    for target in &random_targets {
        let (_, n_visited) = random_tree.find_nearest_neighbor(target);
        total_n_visited += n_visited;
    }
    let search_time = start_search_time.elapsed();
    println!(
        "Visited an average of {} nodes on {} searches in {} ms",
        total_n_visited as f32 / n_searches as f32,
        n_searches,
        search_time.as_millis(),
    );
}

fn quickselect_by<T>(arr: &mut [T], position: usize, cmp: &dyn Fn(&T, &T) -> Ordering) -> T
where
    T: Clone,
{

    let mut pivot_index = thread_rng().gen_range(0, arr.len());

    pivot_index = partition_by(arr, pivot_index, &|a: &T, b: &T| cmp(a, b));
    let array_len = arr.len();
    match position.cmp(&pivot_index) {
        Ordering::Equal => arr[position].clone(),
        Ordering::Less => quickselect_by(&mut arr[0..pivot_index], position, cmp),
        Ordering::Greater => quickselect_by(
            &mut arr[pivot_index + 1..array_len],
            position - pivot_index - 1,
            cmp,
        ),
    }
}

fn partition_by<T>(arr: &mut [T], pivot_index: usize, cmp: &dyn Fn(&T, &T) -> Ordering) -> usize {
    let array_len = arr.len();
    arr.swap(pivot_index, array_len - 1);
    let mut store_index = 0;
    for i in 0..array_len - 1 {
        if cmp(&arr[i], &arr[array_len - 1]) == Less {
            arr.swap(i, store_index);
            store_index += 1;
        }
    }
    arr.swap(array_len - 1, store_index);
    store_index
}


Koch curve

#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>

#define pi M_PI

typedef struct{
	double x,y;
}point;

void kochCurve(point p1,point p2,int times){
	point p3,p4,p5;
	double theta = pi/3;

	if(times>0){
		p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
		p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};

		p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};

		kochCurve(p1,p3,times-1);
		kochCurve(p3,p4,times-1);
		kochCurve(p4,p5,times-1);
		kochCurve(p5,p2,times-1);
	}

	else{
		line(p1.x,p1.y,p2.x,p2.y);
	}
}

int main(int argC, char** argV)
{
	int w,h,r;
	point p1,p2;

	if(argC!=4){
		printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
	}

	else{
		w = atoi(argV[1]);
		h = atoi(argV[2]);
		r = atoi(argV[3]);

		initwindow(w,h,"Koch Curve");

		p1 = (point){10,h-10};
		p2 = (point){w-10,h-10};

		kochCurve(p1,p2,r);

		getch();

		closegraph();
	}

	return 0;
}

use svg::node::element::path::Data;
use svg::node::element::Path;
use svg::node::element::Rectangle;

const SQRT3_2: f64 = 0.86602540378444;

fn koch_curve(mut data: Data, x0: f64, y0: f64, x1: f64, y1: f64, order: usize) -> Data {
    if order == 0 {
        data = data.line_to((x1, y1));
    } else {
        let dx = x1 - x0;
        let dy = y1 - y0;
        let x2 = x0 + dx / 3.0;
        let y2 = y0 + dy / 3.0;
        let x3 = x0 + dx / 2.0 - dy * SQRT3_2 / 3.0;
        let y3 = y0 + dy / 2.0 + dx * SQRT3_2 / 3.0;
        let x4 = x0 + 2.0 * dx / 3.0;
        let y4 = y0 + 2.0 * dy / 3.0;
        data = koch_curve(data, x0, y0, x2, y2, order - 1);
        data = koch_curve(data, x2, y2, x3, y3, order - 1);
        data = koch_curve(data, x3, y3, x4, y4, order - 1);
        data = koch_curve(data, x4, y4, x1, y1, order - 1);
    }
    data
}

fn write_koch_snowflake(file: &str, size: usize, order: usize) -> std::io::Result<()> {
    let length = (size as f64) * SQRT3_2 * 0.95;
    let x0 = ((size as f64) - length) / 2.0;
    let y0 = (size as f64) / 2.0 - length * SQRT3_2 / 3.0;
    let x1 = x0 + length / 2.0;
    let y1 = y0 + length * SQRT3_2;
    let x2 = x0 + length;

    let mut data = Data::new().move_to((x0, y0));
    data = koch_curve(data, x0, y0, x1, y1, order);
    data = koch_curve(data, x1, y1, x2, y0, order);
    data = koch_curve(data, x2, y0, x0, y0, order);

    let path = Path::new()
        .set("fill", "none")
        .set("stroke", "white")
        .set("stroke-width", "1")
        .set("d", data);

    let rect = Rectangle::new()
        .set("width", "100%")
        .set("height", "100%")
        .set("fill", "black");

    let document = svg::Document::new()
        .set("width", size)
        .set("height", size)
        .add(rect)
        .add(path);

    svg::save(file, &document)
}

fn main() {
    write_koch_snowflake("koch_snowflake.svg", 600, 5).unwrap();
}


Kolakoski sequence

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

#define TRUE 1
#define FALSE 0

typedef int bool;

int next_in_cycle(int *c, int len, int index) {
    return c[index % len];
}

void kolakoski(int *c, int *s, int clen, int slen) {
    int i = 0, j, k = 0;
    while (TRUE) {
        s[i] = next_in_cycle(c, clen, k);
        if (s[k] > 1) {
            for (j = 1; j < s[k]; ++j) {
                if (++i == slen) return;
                s[i] = s[i - 1];
            }
        }
        if (++i == slen) return;
        k++;
    }
}

bool possible_kolakoski(int *s, int len) {
    int i, j = 0, prev = s[0], count = 1;
    int *rle = calloc(len, sizeof(int));
    bool result = TRUE;
    for (i = 1; i < len; ++i) {
        if (s[i] == prev) {
            count++;
        }
        else {
            rle[j++] = count;
            count = 1;
            prev = s[i];
        }
    }

    for (i = 0; i < j; i++) {
        if (rle[i] != s[i]) {
           result = FALSE;
           break;
        }
    }
    free(rle);
    return result;
}

void print_array(int *a, int len) {
    int i;
    printf("[");
    for (i = 0; i < len; ++i) {
       printf("%d", a[i]);
       if (i < len - 1) printf(", ");
    }
    printf("]");
}

int main() {
    int i, clen, slen, *s;
    int c0[2] = {1, 2};
    int c1[2] = {2, 1};
    int c2[4] = {1, 3, 1, 2};
    int c3[4] = {1, 3, 2, 1};
    int *cs[4] = {c0, c1, c2, c3};
    bool p;
    int clens[4] = {2, 2, 4, 4};
    int slens[4] = {20, 20, 30, 30};
    for (i = 0; i < 4; ++i) {
        clen = clens[i];
        slen = slens[i];
        s = calloc(slen, sizeof(int));
        kolakoski(cs[i], s, clen, slen);
        printf("First %d members of the sequence generated by ", slen);
        print_array(cs[i], clen);
        printf(":\n");
        print_array(s, slen);
        printf("\n");
        p = possible_kolakoski(s, slen);
        printf("Possible Kolakoski sequence? %s\n\n", p ? "True" : "False");
        free(s);
    }
    return 0;
}

use itertools::Itertools;

fn get_kolakoski_sequence(iseq: &[usize], size: &usize) -> Vec<usize> {
    assert!(*size > 0);
    assert!(!iseq.is_empty());

    let mut kseq: Vec<usize> = Vec::default();

    let repeater = iseq.iter().cloned().cycle();

    kseq.extend_from_slice(&vec![*iseq.get(0).unwrap()].repeat(*iseq.get(0).unwrap()));

    for (k_counter, elem) in repeater.enumerate().skip(1) {

        kseq.push(elem);

        kseq.extend_from_slice(&vec![elem].repeat(*kseq.get(k_counter).unwrap() - 1));

        if kseq.len() >= *size {
            break;
        }
    }

    kseq[0..*size].to_vec()
}

fn is_kolakoski(kseq: &[usize]) -> bool {
    assert!(!kseq.is_empty());

    let rle: Vec<usize> = kseq
        .iter()
        .batching(|it| {
            it.next()
                .map(|v| it.take_while_ref(|&v2| v2 == v).count() + 1)
        })
        .collect();

    rle.iter().zip(kseq).filter(|&(a, b)| a == b).count() == rle.len()
}

fn main() {
    let lengths = vec![20, 20, 30, 30];
    let seqs = vec![vec![1, 2], vec![2, 1], vec![1, 3, 1, 2], vec![1, 3, 2, 1]];

    for (seq, length) in seqs.iter().zip(&lengths) {
        let kseq = get_kolakoski_sequence(&seq, length);

        println!("Starting sequence: {:?}", seq);
        println!("Kolakoski sequence: {:?}", kseq);
        println!("Possible Kolakoski sequence? {:?}", is_kolakoski(&kseq));
    }
}


LU decomposition

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

#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }

typedef double **mat;

#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }

#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
	mat x = malloc(sizeof(double*) * n);
	x[0]  = malloc(sizeof(double) * n * n);

	for_i x[i] = x[0] + n * i;
	_zero(x);

	return x;
}

#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
	mat x = mat_new(n);
	for_ij x[i][j] = ((double (*)[n])s)[i][j];
	return x;
}

#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }

#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
	if (!fmt) fmt = "%8.4g";
	for_i {
		printf(i ? "      " : " [ ");
		for_j {
			printf(fmt, x[i][j]);
			printf(j < n - 1 ? "  " : i == n - 1 ? " ]\n" : "\n");
		}
	}
}

#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
	mat c = _new(c);
	for_ijk c[i][j] += a[i][k] * b[k][j];
	return c;
}

#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
	for_ij { p[i][j] = (i == j); }
	for_i  {
		int max_j = i;
		foreach(j, i, n)
			if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;

		if (max_j != i)
			for_k { _swap(p[i][k], p[max_j][k]); }
	}
}

#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
	_zero(L); _zero(U);
	_pivot(A, P);

	mat Aprime = _mul(P, A);

	for_i  { L[i][i] = 1; }
	for_ij {
		double s;
		if (j <= i) {
			_sum_k(0, j, L[j][k] * U[k][i], s)
			U[j][i] = Aprime[j][i] - s;
		}
		if (j >= i) {
			_sum_k(0, i, L[j][k] * U[k][i], s);
			L[j][i] = (Aprime[j][i] - s) / U[i][i];
		}
	}

	_del(Aprime);
}

double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};

int main()
{
	int n = 3;
	mat A, L, P, U;

	_new(L); _new(P); _new(U);
	A = _copy(A3);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	printf("\n");

	n = 4;

	_new(L); _new(P); _new(U);
	A = _copy(A4);
	_LU(A, L, U, P);
	_show(A); _show(L); _show(U); _show(P);
	_del(A);  _del(L);  _del(U);  _del(P);

	return 0;
}

#![allow(non_snake_case)]
use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};

fn main() {
    println!("Example 1:");
    let A: Array2<f64> = arr2(&[
        [1.0, 3.0, 5.0],
        [2.0, 4.0, 7.0],
        [1.0, 1.0, 0.0],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);

    println!("\nExample 2:");
    let A: Array2<f64> = arr2(&[
        [11.0, 9.0, 24.0, 2.0],
        [1.0, 5.0, 2.0, 6.0],
        [3.0, 17.0, 18.0, 1.0],
        [2.0, 5.0, 7.0, 1.0],
    ]);
    println!("A \n {}", A);
    let (L, U, P) = lu_decomp(A);
    println!("L \n {}", L);
    println!("U \n {}", U);
    println!("P \n {}", P);
}

fn pivot<T>(A: &Array2<T>) -> Array2<T>
where T: NdFloat {
    let matrix_dimension = A.rows();
    let mut P: Array2<T> = Array::eye(matrix_dimension);
    for (i, column) in A.axis_iter(Axis(1)).enumerate() {

        let mut max_pos = i;
        for j in i..matrix_dimension {
            if column[max_pos].abs() < column[j].abs() {
                max_pos = j;
            }
        }

        if max_pos != i {
            swap_rows(&mut P, i, max_pos);
        }
    }
    P
}

fn swap_rows<T>(A: &mut Array2<T>, idx_row1: usize, idx_row2: usize)
where T: NdFloat {

    let (.., mut matrix_rest) = A.view_mut().split_at(Axis(0), idx_row1);
    let (row0, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), 1);
    let (_matrix_helper, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), idx_row2 - idx_row1 - 1);
    let (row1, ..) = matrix_rest.view_mut().split_at(Axis(0), 1);
    Zip::from(row0).and(row1).apply(std::mem::swap);
}

fn lu_decomp<T>(A: Array2<T>) -> (Array2<T>, Array2<T>, Array2<T>)
where T: NdFloat {

    let matrix_dimension = A.rows();
    assert_eq!(matrix_dimension, A.cols(), "Tried LU decomposition with a non-square matrix.");
    let P = pivot(&A);
    let pivotized_A = P.dot(&A);

    let mut L: Array2<T> = Array::eye(matrix_dimension);
    let mut U: Array2<T> = Array::zeros((matrix_dimension, matrix_dimension));
    for idx_col in 0..matrix_dimension {

        for idx_row in 0..idx_col+1 {
            U[[idx_row, idx_col]] = pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_row,idx_col]).dot(&L.slice(s![idx_row,0..idx_row]));
        }

        for idx_row in idx_col+1..matrix_dimension {
            L[[idx_row, idx_col]] = (pivotized_A[[idx_row, idx_col]] -
                U.slice(s![0..idx_col,idx_col]).dot(&L.slice(s![idx_row,0..idx_col]))) /
                U[[idx_col, idx_col]];
        }
    }
    (L, U, P)
}


Largest prime factor

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

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

int main(void) {
    long int n=600851475143, j=3;

    while(!isprime(n)) {
        if(!(n%j)) n/=j;
        j+=2;
    }
    printf( "%ld\n", n );
    return 0;
}

fn main( ) {
   let mut current : i64 = 600851475143 ;
   let mut latest_divisor : i64 = 2 ;
   while current != 1 {
      latest_divisor = 2 ;
      while current % latest_divisor != 0 {
         latest_divisor += 1 ;
      }
      current /= latest_divisor ;
   }
   println!("{}" , latest_divisor ) ;
}


Left factorials

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

void mpz_left_fac_ui(mpz_t rop, unsigned long op)
{
    mpz_t t1;
    mpz_init_set_ui(t1, 1);
    mpz_set_ui(rop, 0);

    size_t i;
    for (i = 1; i <= op; ++i) {
        mpz_add(rop, rop, t1);
        mpz_mul_ui(t1, t1, i);
    }

    mpz_clear(t1);
}

size_t mpz_digitcount(mpz_t op)
{

    char *t    = mpz_get_str(NULL, 10, op);
    size_t ret = strlen(t);
    free(t);
    return ret;
}

int main(void)
{
    mpz_t t;
    mpz_init(t);
    size_t i;

    for (i = 0; i <= 110; ++i) {
        if (i <= 10 || i % 10 == 0) {
            mpz_left_fac_ui(t, i);
            gmp_printf("!%u = %Zd\n", i, t);
        }
    }

    for (i = 1000; i <= 10000; i += 1000) {
        mpz_left_fac_ui(t, i);
        printf("!%u has %u digits\n", i, mpz_digitcount(t));
    }

    mpz_clear(t);
    return 0;
}

#[cfg(target_pointer_width = "64")]
type USingle = u32;
#[cfg(target_pointer_width = "64")]
type UDouble = u64;
#[cfg(target_pointer_width = "64")]
const WORD_LEN: i32 = 32;

#[cfg(not(target_pointer_width = "64"))]
type USingle = u16;
#[cfg(not(target_pointer_width = "64"))]
type UDouble = u32;
#[cfg(not(target_pointer_width = "64"))]
const WORD_LEN: i32 = 16;

use std::cmp;

#[derive(Debug,Clone)]
struct BigNum {

    rep_: Vec<USingle>,
}

impl BigNum {
    pub fn new(n: USingle) -> BigNum {
        let mut result = BigNum { rep_: vec![] };
        if n > 0 { result.rep_.push(n); }
        result
    }
    pub fn equals(&self, n: USingle) -> bool {
        if n == 0 { return self.rep_.is_empty() }
        if self.rep_.len() > 1 { return false }
        self.rep_[0] == n
    }
    pub fn add_big(&self, addend: &BigNum) -> BigNum {
        let mut result = BigNum::new(0);
        let mut sum = 0 as UDouble;
        let sz1 = self.rep_.len();
        let sz2 = addend.rep_.len();
        for i in 0..cmp::max(sz1, sz2) {
            if i < sz1 { sum += self.rep_[i] as UDouble }
            if i < sz2 { sum += addend.rep_[i] as UDouble }
            result.rep_.push(sum as USingle);
            sum >>= WORD_LEN;
        }
        if sum > 0 { result.rep_.push(sum as USingle) }
        result
    }
    pub fn multiply(&self, factor: USingle) -> BigNum {
        let mut result = BigNum::new(0);
        let mut product = 0 as UDouble;
        for i in 0..self.rep_.len() {
            product += self.rep_[i] as UDouble * factor as UDouble;
            result.rep_.push(product as USingle);
            product >>= WORD_LEN;
        }
        if product > 0 {
            result.rep_.push(product as USingle);
        }
        result
    }
    pub fn divide(&self, divisor: USingle, quotient: &mut BigNum,
        remainder: &mut USingle) {
        quotient.rep_.truncate(0);
        let mut dividend: UDouble;
        *remainder = 0;
        for i in 0..self.rep_.len() {
            let j = self.rep_.len() - 1 - i;
            dividend = ((*remainder as UDouble) << WORD_LEN)
                + self.rep_[j] as UDouble;
            let quo = (dividend / divisor as UDouble) as USingle;
            *remainder = (dividend % divisor as UDouble) as USingle;
            if quo > 0 || j < self.rep_.len() - 1 {
                quotient.rep_.push(quo);
            }
        }
        quotient.rep_.reverse();
    }
    fn to_string(&self) -> String {
        let mut rep = String::new();
        let mut dividend = (*self).clone();
        let mut remainder = 0 as USingle;
        let mut quotient = BigNum::new(0);
        loop {
            dividend.divide(10, &mut quotient, &mut remainder);
            rep.push(('0' as USingle + remainder) as u8 as char);
            if quotient.equals(0) { break; }
            dividend = quotient.clone();
        }
        rep.chars().rev().collect::<String>()
    }
}

use std::fmt;
impl fmt::Display for BigNum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

fn lfact(n: USingle) -> BigNum {
    let mut result = BigNum::new(0);
    let mut f = BigNum::new(1);
    for k in 1 as USingle..n + 1 {
        result = result.add_big(&f);
        f = f.multiply(k);
    }
    result
}

fn main() {
    for i in 0..11 {
        println!("!{} = {}", i, lfact(i));
    }
    for i in 2..12 {
        let j = i * 10;
        println!("!{} = {}", j, lfact(j));
    }
    for i in 1..11 {
        let j = i * 1000;
        println!("!{} has {} digits.", j, lfact(j).to_string().len());
    }
}


Levenshtein distance_Alignment

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

typedef struct edit_s edit_t, *edit;
struct edit_s {
	char c1, c2;
	int n;
	edit next;
};

void leven(char *a, char *b)
{
	int i, j, la = strlen(a), lb = strlen(b);
	edit *tbl = malloc(sizeof(edit) * (1 + la));
	tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));
	for (i = 1; i <= la; i++)
		tbl[i] = tbl[i-1] + (1+lb);

	for (i = la; i >= 0; i--) {
		char *aa = a + i;
		for (j = lb; j >= 0; j--) {
			char *bb = b + j;
			if (!*aa && !*bb) continue;

			edit e = &tbl[i][j];
			edit repl = &tbl[i+1][j+1];
			edit dela = &tbl[i+1][j];
			edit delb = &tbl[i][j+1];

			e->c1 = *aa;
			e->c2 = *bb;
			if (!*aa) {
				e->next = delb;
				e->n = e->next->n + 1;
				continue;
			}
			if (!*bb) {
				e->next = dela;
				e->n = e->next->n + 1;
				continue;
			}

			e->next = repl;
			if (*aa == *bb) {
				e->n = e->next->n;
				continue;
			}

			if (e->next->n > delb->n) {
				e->next = delb;
				e->c1 = 0;
			}
			if (e->next->n > dela->n) {
				e->next = dela;
				e->c1 = *aa;
				e->c2 = 0;
			}
			e->n = e->next->n + 1;
		}
	}

	edit p = tbl[0];
	printf("%s -> %s: %d edits\n", a, b, p->n);

	while (p->next) {
		if (p->c1 == p->c2)
			printf("%c", p->c1);
		else {
			putchar('(');
			if (p->c1) putchar(p->c1);
			putchar(',');
			if (p->c2) putchar(p->c2);
			putchar(')');
		}

		p = p->next;
	}
	putchar('\n');

	free(tbl[0]);
	free(tbl);
}

int main(void)
{
	leven("raisethysword", "rosettacode");
	return 0;
}

extern crate edit_distance;

edit_distance("rosettacode", "raisethysword");