Line circle intersection

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

const double eps = 1e-14;

typedef struct point_t {
    double x, y;
} point;

point make_point(double x, double y) {
    point p = { x, y };
    return p;
}

void print_point(point p) {
    double x = p.x;
    double y = p.y;
    if (x == 0) {
        x = 0;
    }
    if (y == 0) {
        y = 0;
    }
    printf("(%g, %g)", x, y);
}

double sq(double x) {
    return x * x;
}

bool within(double x1, double y1, double x2, double y2, double x, double y) {
    double d1 = sqrt(sq(x2 - x1) + sq(y2 - y1));
    double d2 = sqrt(sq(x - x1) + sq(y - y1));
    double d3 = sqrt(sq(x2 - x) + sq(y2 - y));
    double delta = d1 - d2 - d3;
    return fabs(delta) < eps;
}

int rxy(double x1, double y1, double x2, double y2, double x, double y, bool segment) {
    if (!segment || within(x1, y1, x2, y2, x, y)) {
        print_point(make_point(x, y));
        return 1;
    } else {
        return 0;
    }
}

double fx(double A, double B, double C, double x) {
    return -(A * x + C) / B;
}

double fy(double A, double B, double C, double y) {
    return -(B * y + C) / A;
}

void intersects(point p1, point p2, point cp, double r, bool segment) {
    double x0 = cp.x, y0 = cp.y;
    double x1 = p1.x, y1 = p1.y;
    double x2 = p2.x, y2 = p2.y;
    double A = y2 - y1;
    double B = x1 - x2;
    double C = x2 * y1 - x1 * y2;
    double a = sq(A) + sq(B);
    double b, c, d;
    bool bnz = true;
    int cnt = 0;

    if (fabs(B) >= eps) {

        b = 2 * (A * C + A * B * y0 - sq(B) * x0);
        c = sq(C) + 2 * B * C * y0 - sq(B) * (sq(r) - sq(x0) - sq(y0));
    } else {
        b = 2 * (B * C + A * B * x0 - sq(A) * y0);
        c = sq(C) + 2 * A * C * x0 - sq(A) * (sq(r) - sq(x0) - sq(y0));
        bnz = false;
    }
    d = sq(b) - 4 * a * c;
    if (d < 0) {

        printf("[]\n");
        return;
    }

    if (d == 0) {

        if (bnz) {
            double x = -b / (2 * a);
            double y = fx(A, B, C, x);
            cnt = rxy(x1, y1, x2, y2, x, y, segment);
        } else {
            double y = -b / (2 * a);
            double x = fy(A, B, C, y);
            cnt = rxy(x1, y1, x2, y2, x, y, segment);
        }
    } else {

        d = sqrt(d);
        if (bnz) {
            double x = (-b + d) / (2 * a);
            double y = fx(A, B, C, x);
            cnt = rxy(x1, y1, x2, y2, x, y, segment);

            x = (-b - d) / (2 * a);
            y = fx(A, B, C, x);
            cnt += rxy(x1, y1, x2, y2, x, y, segment);
        } else {
            double y = (-b + d) / (2 * a);
            double x = fy(A, B, C, y);
            cnt = rxy(x1, y1, x2, y2, x, y, segment);

            y = (-b - d) / (2 * a);
            x = fy(A, B, C, y);
            cnt += rxy(x1, y1, x2, y2, x, y, segment);
        }
    }

    if (cnt <= 0) {
        printf("[]");
    }
}

int main() {
    point cp = make_point(3, -5);
    double r = 3.0;
    printf("The intersection points (if any) between:\n");
    printf("  A circle, center (3, -5) with radius 3, and:\n");
    printf("    a line containing the points (-10, 11) and (10, -9) is/are:\n");
    printf("      ");
    intersects(make_point(-10, 11), make_point(10, -9), cp, r, false);
    printf("\n    a segment starting at (-10, 11) and ending at (-11, 12) is/are\n");
    printf("      ");
    intersects(make_point(-10, 11), make_point(-11, 12), cp, r, true);
    printf("\n    a horizontal line containing the points (3, -2) and (7, -2) is/are:\n");
    printf("      ");
    intersects(make_point(3, -2), make_point(7, -2), cp, r, false);
    printf("\n");

    cp = make_point(0, 0);
    r = 4.0;
    printf("  A circle, center (0, 0) with radius 4, and:\n");
    printf("    a vertical line containing the points (0, -3) and (0, 6) is/are:\n");
    printf("      ");
    intersects(make_point(0, -3), make_point(0, 6), cp, r, false);
    printf("\n    a vertical segment starting at (0, -3) and ending at (0, 6) is/are:\n");
    printf("      ");
    intersects(make_point(0, -3), make_point(0, 6), cp, r, true);
    printf("\n");

    cp = make_point(4,2);
    r = 5.0;
    printf("  A circle, center (4, 2) with radius 5, and:\n");
    printf("    a line containing the points (6, 3) and (10, 7) is/are:\n");
    printf("      ");
    intersects(make_point(6, 3), make_point(10, 7), cp, r, false);
    printf("\n    a segment starting at (7, 4) and ending at (11, 8) is/are:\n");
    printf("      ");
    intersects(make_point(7, 4), make_point(11, 8), cp, r, true);
    printf("\n");

    return 0;
}

use assert_approx_eq::assert_approx_eq;

const EPS: f64 = 1e-14;

pub struct Point {
    x: f64,
    y: f64,
}

pub struct Line {
    p1: Point,
    p2: Point,
}

impl Line {
    pub fn circle_intersections(&self, mx: f64, my: f64, r: f64, segment: bool) -> Vec<Point> {
        let mut intersections: Vec<Point> = Vec::new();

        let x0 = mx;
        let y0 = my;
        let x1 = self.p1.x;
        let y1 = self.p1.y;
        let x2 = self.p2.x;
        let y2 = self.p2.y;

        let ca = y2 - y1;
        let cb = x1 - x2;
        let cc = x2 * y1 - x1 * y2;

        let a = ca.powi(2) + cb.powi(2);
        let mut b = 0.0;
        let mut c = 0.0;
        let mut bnz = true;

        if cb.abs() >= EPS {
            b = 2.0 * (ca * cc + ca * cb * y0 - cb.powi(2) * x0);
            c = cc.powi(2) + 2.0 * cb * cc * y0
                - cb.powi(2) * (r.powi(2) - x0.powi(2) - y0.powi(2));
        } else {
            b = 2.0 * (cb * cc + ca * cb * x0 - ca.powi(2) * y0);
            c = cc.powi(2) + 2.0 * ca * cc * x0
                - ca.powi(2) * (r.powi(2) - x0.powi(2) - y0.powi(2));
            bnz = false;
        }
        let mut d = b.powi(2) - 4.0 * a * c;
        if d < 0.0 {
            return intersections;
        }

        fn within(x: f64, y: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> bool {
            let d1 = ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt();
            let d2 = ((x - x1).powi(2) + (y - y1).powi(2)).sqrt();
            let d3 = ((x2 - x).powi(2) + (y2 - y).powi(2)).sqrt();
            let delta = d1 - d2 - d3;
            return delta.abs() < EPS;
        }

        fn fx(x: f64, ca: f64, cb: f64, cc: f64) -> f64 {
            -(ca * x + cc) / cb
        }

        fn fy(y: f64, ca: f64, cb: f64, cc: f64) -> f64 {
            -(cb * y + cc) / ca
        }

        fn rxy(
            x: f64,
            y: f64,
            x1: f64,
            y1: f64,
            x2: f64,
            y2: f64,
            segment: bool,
            intersections: &mut Vec<Point>,
        ) {
            if !segment || within(x, y, x1, y1, x2, y2) {
                let point = Point { x: x, y: y };
                intersections.push(point);
            }
        }

        if d == 0.0 {
            if bnz {
                let x = -b / (2.0 * a);
                let y = fx(x, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
            } else {
                let y = -b / (2.0 * a);
                let x = fy(y, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
            }
        } else {
            d = d.sqrt();
            if bnz {
                let x = (-b + d) / (2.0 * a);
                let y = fx(x, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
                let x = (-b - d) / (2.0 * a);
                let y = fx(x, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
            } else {
                let y = (-b + d) / (2.0 * a);
                let x = fy(y, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
                let y = (-b - d) / (2.0 * a);
                let x = fy(y, ca, cb, cc);
                rxy(x, y, x1, y1, x2, y2, segment, &mut intersections);
            }
        }

        intersections.sort_unstable_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
        intersections
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_circle_line_intersections() {
        let mut p1 = Point { x: -10.0, y: 11.0 };
        let mut p2 = Point { x: 10.0, y: -9.0 };
        let mut line = Line { p1: p1, p2: p2 };

        let result1 = line.circle_intersections(3.0, -5.0, 3.0, false);
        assert_eq!(result1.len(), 2);
        assert_approx_eq!(result1[0].x, 3.0);
        assert_approx_eq!(result1[0].y, -2.0);
        assert_approx_eq!(result1[1].x, 6.0);
        assert_approx_eq!(result1[1].y, -5.0);

        p1 = Point { x: -10.0, y: 11.0 };
        p2 = Point { x: -11.0, y: -12.0 };
        line = Line { p1: p1, p2: p2 };
        let result2 = line.circle_intersections(3.0, -5.0, 3.0, true);
        assert_eq!(result2.len(), 0);

        p1 = Point { x: 3.0, y: -2.0 };
        p2 = Point { x: 7.0, y: -2.0 };
        line = Line { p1, p2 };
        let result3 = line.circle_intersections(3.0, -5.0, 3.0, true);
        assert_eq!(result3.len(), 1);
        assert_approx_eq!(result3[0].x, 3.0);
        assert_approx_eq!(result3[0].y, -2.0);

        p1 = Point { x: 0.0, y: -3.0 };
        p2 = Point { x: 0.0, y: 6.0 };
        line = Line { p1, p2 };
        let result4 = line.circle_intersections(0.0, 0.0, 4.0, false);
        assert_eq!(result4.len(), 2);
        assert_approx_eq!(result4[0].x, 0.0);
        assert_approx_eq!(result4[1].x, 0.0);

        let result5 = line.circle_intersections(0.0, 0.0, 4.0, true);
        assert_eq!(result5.len(), 1);

        p1 = Point { x: 6.0, y: 3.0 };
        p2 = Point { x: 10.0, y: 7.0 };
        line = Line { p1, p2 };
        let result6 = line.circle_intersections(4.0, 2.0, 5.0, false);
        assert_eq!(result6.len(), 2);
        assert_approx_eq!(result6[0].x, 1.0);
        assert_approx_eq!(result6[0].y, -2.0);
        assert_approx_eq!(result6[1].x, 8.0);
        assert_approx_eq!(result6[1].y, 5.0);

        p1 = Point { x: 7.0, y: 4.0 };
        p2 = Point { x: 11.0, y: 8.0 };
        line = Line { p1, p2 };
        let result7 = line.circle_intersections(4.0, 2.0, 5.0, true);
        assert_eq!(result7.len(), 1);
        assert_approx_eq!(result7[0].x, 8.0);
        assert_approx_eq!(result7[0].y, 5.0);
    }
}


Long primes

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

#define TRUE 1
#define FALSE 0

typedef int bool;

void sieve(int limit, int primes[], int *count) {
    bool *c = calloc(limit + 1, sizeof(bool));

    int i, p = 3, p2, n = 0;
    p2 = p * p;
    while (p2 <= limit) {
        for (i = p2; i <= limit; i += 2 * p)
            c[i] = TRUE;
        do {
            p += 2;
        } while (c[p]);
        p2 = p * p;
    }
    for (i = 3; i <= limit; i += 2) {
        if (!c[i]) primes[n++] = i;
    }
    *count = n;
    free(c);
}

int findPeriod(int n) {
    int i, r = 1, rr, period = 0;
    for (i = 1; i <= n + 1; ++i) {
        r = (10 * r) % n;
    }
    rr = r;
    do {
        r = (10 * r) % n;
        period++;
    } while (r != rr);
    return period;
}

int main() {
    int i, prime, count = 0, index = 0, primeCount, longCount = 0, numberCount;
    int *primes, *longPrimes, *totals;
    int numbers[] = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000};

    primes = calloc(6500, sizeof(int));
    numberCount = sizeof(numbers) / sizeof(int);
    totals = calloc(numberCount, sizeof(int));
    sieve(64000, primes, &primeCount);
    longPrimes = calloc(primeCount, sizeof(int));

    for (i = 0; i < primeCount; ++i) {
        prime = primes[i];
        if (findPeriod(prime) == prime - 1) {
            longPrimes[longCount++] = prime;
        }
    }
    for (i = 0; i < longCount; ++i, ++count) {
        if (longPrimes[i] > numbers[index]) {
            totals[index++] = count;
        }
    }
    totals[numberCount - 1] = count;
    printf("The long primes up to %d are:\n", numbers[0]);
    printf("[");
    for (i = 0; i < totals[0]; ++i) {
        printf("%d ", longPrimes[i]);
    }
    printf("\b]\n");

    printf("\nThe number of long primes up to:\n");
    for (i = 0; i < 8; ++i) {
        printf("  %5d is %d\n", numbers[i], totals[i]);
    }
    free(totals);
    free(longPrimes);
    free(primes);
    return 0;
}

mod bit_array;
mod prime_sieve;

use prime_sieve::PrimeSieve;

fn modpow(mut base: usize, mut exp: usize, n: usize) -> usize {
    if n == 1 {
        return 0;
    }
    let mut result = 1;
    base %= n;
    while exp > 0 {
        if (exp & 1) == 1 {
            result = (result * base) % n;
        }
        base = (base * base) % n;
        exp >>= 1;
    }
    result
}

fn is_long_prime(sieve: &PrimeSieve, prime: usize) -> bool {
    if !sieve.is_prime(prime) {
        return false;
    }
    if 10 % prime == 0 {
        return false;
    }
    let n = prime - 1;
    let mut m = n;
    let mut p = 2;
    while p * p <= n {
        if sieve.is_prime(p) && m % p == 0 {
            if modpow(10, n / p, prime) == 1 {
                return false;
            }
            while m % p == 0 {
                m /= p;
            }
        }
        p += 1;
    }
    if m == 1 {
        return true;
    }
    modpow(10, n / m, prime) != 1
}

fn long_primes(limit1: usize, limit2: usize) {
    let sieve = PrimeSieve::new(limit2);
    let mut count = 0;
    let mut limit = limit1;
    let mut prime = 3;
    while prime < limit2 {
        if is_long_prime(&sieve, prime) {
            if prime < limit1 {
                print!("{} ", prime);
            }
            if prime > limit {
                print!("\nNumber of long primes up to {}: {}", limit, count);
                limit *= 2;
            }
            count += 1;
        }
        prime += 2;
    }
    println!("\nNumber of long primes up to {}: {}", limit, count);
}

fn main() {
    long_primes(500, 8192000);
}


Longest increasing subsequence

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

struct node {
	int val, len;
	struct node *next;
};

void lis(int *v, int len)
{
	int i;
	struct node *p, *n = calloc(len, sizeof *n);
	for (i = 0; i < len; i++)
		n[i].val = v[i];

	for (i = len; i--; ) {

		for (p = n + i; p++ < n + len; ) {
			if (p->val > n[i].val && p->len >= n[i].len) {
				n[i].next = p;
				n[i].len = p->len + 1;
			}
		}
	}

	for (i = 0, p = n; i < len; i++)
		if (n[i].len > p->len) p = n + i;

	do printf(" %d", p->val); while ((p = p->next));
	putchar('\n');

	free(n);
}

int main(void)
{
	int x[] = { 3, 2, 6, 4, 5, 1 };
	int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };

	lis(x, sizeof(x) / sizeof(int));
	lis(y, sizeof(y) / sizeof(int));
	return 0;
}

fn lis(x: &[i32])-> Vec<i32> {
    let n = x.len();
    let mut m = vec![0; n];
    let mut p = vec![0; n];
    let mut l = 0;

    for i in 0..n {
        let mut lo = 1;
        let mut hi = l;

        while lo <= hi {
            let mid = (lo + hi) / 2;

            if x[m[mid]] <= x[i] {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        let new_l = lo;
        p[i] = m[new_l - 1];
        m[new_l] = i;

        if new_l > l {
            l = new_l;
        }
    }

    let mut o = vec![0; l];
    let mut k = m[l];
    for i in (0..l).rev() {
        o[i] = x[k];
        k    = p[k];
    }

    o
}

fn main() {
    let list = vec![3, 2, 6, 4, 5, 1];
    println!("{:?}", lis(&list));
    let list = vec![0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
    println!("{:?}", lis(&list));
}


fn main() {
    loop {
        println!("SPAM");
    }
}


Machine code

#include <stdio.h>
#include <sys/mman.h>
#include <string.h>

int test (int a, int b)
{

  char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
  void *buf;
  int c;

  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
             MAP_PRIVATE|MAP_ANON,-1,0);

  memcpy (buf, code, sizeof(code));

  c = ((int (*) (int, int))buf)(a, b);

  munmap (buf, sizeof(code));
  return c;
}

int main ()
{
  printf("%d\n", test(7,12));
  return 0;
}

extern crate libc;

#[cfg(all(
    target_os = "linux",
    any(target_pointer_width = "32", target_pointer_width = "64")
))]
fn main() {
    use std::mem;
    use std::ptr;

    let page_size: usize = 4096;
    let (bytes, size): (Vec<u8>, usize) = if cfg!(target_pointer_width = "32") {
        (
            vec![0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3],
            9,
        )
    } else {
        (vec![0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3], 7)
    };
    let f: fn(u8, u8) -> u8 = unsafe {
        let mut page: *mut libc::c_void = ptr::null_mut();
        libc::posix_memalign(&mut page, page_size, size);
        libc::mprotect(
            page,
            size,
            libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
        );
        let contents: *mut u8 = page as *mut u8;
        ptr::copy(bytes.as_ptr(), contents, 9);
        mem::transmute(contents)
    };

    let return_value = f(7, 12);
    println!("Returned value: {}", return_value);
    assert_eq!(return_value, 19);
}

#[cfg(any(
    not(target_os = "linux"),
    not(any(target_pointer_width = "32", target_pointer_width = "64"))
))]
fn main() {
    println!("Not supported on this platform.");
}


Magic squares of doubly even order

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

int** doublyEvenMagicSquare(int n) {
	if (n < 4 || n % 4 != 0)
		return NULL;

	int bits = 38505;
	int size = n * n;
	int mult = n / 4,i,r,c,bitPos;

	int** result = (int**)malloc(n*sizeof(int*));

	for(i=0;i<n;i++)
		result[i] = (int*)malloc(n*sizeof(int));

	for (r = 0, i = 0; r < n; r++) {
		for (c = 0; c < n; c++, i++) {
			bitPos = c / mult + (r / mult) * 4;
			result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
		}
	}
	return result;
}

int numDigits(int n){
	int count = 1;

	while(n>=10){
		n /= 10;
		count++;
	}

	return count;
}

void printMagicSquare(int** square,int rows){
	int i,j,baseWidth = numDigits(rows*rows) + 3;

	printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);

	for(i=0;i<rows;i++){
		for(j=0;j<rows;j++){
			printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
		}
		printf("\n");
	}
}

int main(int argC,char* argV[])
{
	int n;

	if(argC!=2||isdigit(argV[1][0])==0)
		printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
	else{
		n = atoi(argV[1]);
		printMagicSquare(doublyEvenMagicSquare(n),n);
	}
	return 0;
}

use std::env;

fn main() {
    let n: usize = match env::args()
        .nth(1)
        .and_then(|arg| arg.parse().ok())
        .ok_or("Please specify the size of the magic square, as a positive multiple of 4.")
    {
        Ok(arg) if arg >= 4 && arg % 4 == 0 => arg,
        Err(e) => panic!(e),
        _ => panic!("Argument must be a positive multiple of 4."),
    };

    let mc = (n * n + 1) * n / 2;
    println!("Magic constant: {}\n", mc);
    let bits = 0b1001_0110_0110_1001u32;
    let size = n * n;
    let width = size.to_string().len() + 1;
    let mult = n / 4;
    let mut i = 0;
    for r in 0..n {
        for c in 0..n {
            let bit_pos = c / mult + (r / mult) * 4;
            print!(
                "{e:>w$}",
                e = if bits & (1 << bit_pos) != 0 {
                    i + 1
                } else {
                    size - i
                },
                w = width
            );
            i += 1;
        }
        println!();
    }
}


Magic squares of singly even order

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

   int** oddMagicSquare(int n) {
        if (n < 3 || n % 2 == 0)
            return NULL;

        int value = 0;
        int squareSize = n * n;
        int c = n / 2, r = 0,i;

        int** result = (int**)malloc(n*sizeof(int*));

		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));

        while (++value <= squareSize) {
            result[r][c] = value;
            if (r == 0) {
                if (c == n - 1) {
                    r++;
                } else {
                    r = n - 1;
                    c++;
                }
            } else if (c == n - 1) {
                r--;
                c = 0;
            } else if (result[r - 1][c + 1] == 0) {
                r--;
                c++;
            } else {
                r++;
            }
        }
        return result;
    }

    int** singlyEvenMagicSquare(int n) {
        if (n < 6 || (n - 2) % 4 != 0)
            return NULL;

        int size = n * n;
        int halfN = n / 2;
        int subGridSize = size / 4, i;

        int** subGrid = oddMagicSquare(halfN);
        int gridFactors[] = {0, 2, 3, 1};
        int** result = (int**)malloc(n*sizeof(int*));

		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));

        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                int grid = (r / halfN) * 2 + (c / halfN);
                result[r][c] = subGrid[r % halfN][c % halfN];
                result[r][c] += gridFactors[grid] * subGridSize;
            }
        }

        int nColsLeft = halfN / 2;
        int nColsRight = nColsLeft - 1;

        for (int r = 0; r < halfN; r++)
            for (int c = 0; c < n; c++) {
                if (c < nColsLeft || c >= n - nColsRight
                        || (c == nColsLeft && r == nColsLeft)) {

                    if (c == 0 && r == nColsLeft)
                        continue;

                    int tmp = result[r][c];
                    result[r][c] = result[r + halfN][c];
                    result[r + halfN][c] = tmp;
                }
            }

        return result;
    }

	int numDigits(int n){
		int count = 1;

		while(n>=10){
			n /= 10;
			count++;
		}

		return count;
	}

	void printMagicSquare(int** square,int rows){
		int i,j;

		for(i=0;i<rows;i++){
			for(j=0;j<rows;j++){
				printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
			}
			printf("\n");
		}
		printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
	}

	int main(int argC,char* argV[])
	{
		int n;

		if(argC!=2||isdigit(argV[1][0])==0)
			printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
		else{
			n = atoi(argV[1]);
			printMagicSquare(singlyEvenMagicSquare(n),n);
		}
		return 0;
	}

use std::env;

fn main() {
    let n: usize =
        match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or(
            "Please specify the size of the magic square, as a positive multiple of 4 plus 2.",
        ) {
            Ok(arg) if arg % 2 == 1 || arg >= 6 && (arg - 2) % 4 == 0 => arg,
            Err(e) => panic!(e),
            _ => panic!("Argument must be a positive multiple of 4 plus 2."),
        };

    let (ms, mc) = magic_square_singly_even(n);
    println!("n: {}", n);
    println!("Magic constant: {}\n", mc);
    let width = (n * n).to_string().len() + 1;
    for row in ms {
        for elem in row {
            print!("{e:>w$}", e = elem, w = width);
        }
        println!();
    }
}

fn magic_square_singly_even(n: usize) -> (Vec<Vec<usize>>, usize) {
    let size = n * n;
    let half = n / 2;
    let sub_square_size = size / 4;
    let sub_square = magic_square_odd(half);
    let quadrant_factors = [0, 2, 3, 1];
    let cols_left = half / 2;
    let cols_right = cols_left - 1;

    let ms = (0..n)
        .map(|r| {
            (0..n)
                .map(|c| {
                    let localr = if (c < cols_left
                        || c >= n - cols_right
                        || c == cols_left && r % half == cols_left)
                        && !(c == 0 && r % half == cols_left)
                    {
                        if r >= half {
                            r - half
                        } else {
                            r + half
                        }
                    } else {
                        r
                    };
                    let quadrant = localr / half * 2 + c / half;
                    let v = sub_square[localr % half][c % half];
                    v + quadrant_factors[quadrant] * sub_square_size
                })
                .collect()
        })
        .collect::<Vec<Vec<_>>>();
    (ms, (n * n + 1) * n / 2)
}

fn magic_square_odd(n: usize) -> Vec<Vec<usize>> {
    (0..n)
        .map(|r| {
            (0..n)
                .map(|c| {
                    n * (((c + 1) + (r + 1) - 1 + (n >> 1)) % n)
                        + (((c + 1) + (2 * (r + 1)) - 2) % n)
                        + 1
                })
                .collect::<Vec<_>>()
        })
        .collect::<Vec<Vec<_>>>()
}


Magnanimous numbers

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

typedef int bool;
typedef unsigned long long ull;

#define TRUE 1
#define FALSE 0

bool is_prime(ull n) {
    ull d;
    if (n < 2) return FALSE;
    if (!(n % 2)) return n == 2;
    if (!(n % 3)) return n == 3;
    d = 5;
    while (d * d <= n) {
        if (!(n % d)) return FALSE;
        d += 2;
        if (!(n % d)) return FALSE;
        d += 4;
    }
    return TRUE;
}

void ord(char *res, int n) {
    char suffix[3];
    int m = n % 100;
    if (m >= 4 && m <= 20) {
        sprintf(res,"%dth", n);
        return;
    }
    switch(m % 10) {
        case 1:
            strcpy(suffix, "st");
            break;
        case 2:
            strcpy(suffix, "nd");
            break;
        case 3:
            strcpy(suffix, "rd");
            break;
        default:
            strcpy(suffix, "th");
            break;
    }
    sprintf(res, "%d%s", n, suffix);
}

bool is_magnanimous(ull n) {
    ull p, q, r;
    if (n < 10) return TRUE;
    for (p = 10; ; p *= 10) {
        q = n / p;
        r = n % p;
        if (!is_prime(q + r)) return FALSE;
        if (q < 10) break;
    }
    return TRUE;
}

void list_mags(int from, int thru, int digs, int per_line) {
    ull i = 0;
    int c = 0;
    char res1[13], res2[13];
    if (from < 2) {
        printf("\nFirst %d magnanimous numbers:\n", thru);
    } else {
        ord(res1, from);
        ord(res2, thru);
        printf("\n%s through %s magnanimous numbers:\n", res1, res2);
    }
    for ( ; c < thru; ++i) {
        if (is_magnanimous(i)) {
            if (++c >= from) {
                printf("%*llu ", digs, i);
                if (!(c % per_line)) printf("\n");
            }
        }
    }
}

int main() {
    list_mags(1, 45, 3, 15);
    list_mags(241, 250, 1, 10);
    list_mags(391, 400, 1, 10);
    return 0;
}

fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    let mut p = 5;
    while p * p <= n {
        if n % p == 0 {
            return false;
        }
        p += 2;
        if n % p == 0 {
            return false;
        }
        p += 4;
    }
    true
}

fn is_magnanimous(n: u32) -> bool {
    let mut p: u32 = 10;
    while n >= p {
        if !is_prime(n % p + n / p) {
            return false;
        }
        p *= 10;
    }
    true
}

fn main() {
    let mut m = (0..).filter(|x| is_magnanimous(*x)).take(400);
    println!("First 45 magnanimous numbers:");
    for (i, n) in m.by_ref().take(45).enumerate() {
        if i > 0 && i % 15 == 0 {
            println!();
        }
        print!("{:3} ", n);
    }
    println!("\n\n241st through 250th magnanimous numbers:");
    for n in m.by_ref().skip(195).take(10) {
        print!("{} ", n);
    }
    println!("\n\n391st through 400th magnanimous numbers:");
    for n in m.by_ref().skip(140) {
        print!("{} ", n);
    }
    println!();
}


Mayan numerals

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

#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))

size_t base20(unsigned int n, uint8_t *out) {

    uint8_t *start = out;
    do {*out++ = n % 20;} while (n /= 20);
    size_t length = out - start;

    while (out > start) {
        uint8_t x = *--out;
        *out = *start;
        *start++ = x;
    }
    return length;
}

void make_digit(int n, char *place, size_t line_length) {
    static const char *parts[] = {"    "," .  "," .. ","... ","....","----"};
    int i;

    for (i=4; i>0; i--, n -= 5)
        memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);

    if (n == -20) place[4 * line_length + 1] = '@';
}

char *mayan(unsigned int n) {
    if (n == 0) return NULL;

    uint8_t digits[15];
    size_t n_digits = base20(n, digits);

    size_t line_length = n_digits*5 + 2;

    char *str = malloc(line_length * 6 + 1);
    if (str == NULL) return NULL;
    str[line_length * 6] = 0;

    char *ptr;
    unsigned int i;

    for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
        memcpy(ptr, "+----", 5);
    memcpy(ptr-5, "+\n", 2);
    memcpy(str+5*line_length, str, line_length);

    for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
        memcpy(ptr, "|    ", 5);
    memcpy(ptr-5, "|\n", 2);
    memcpy(str+2*line_length, str+line_length, line_length);
    memcpy(str+3*line_length, str+line_length, 2*line_length);

    for (i=0; i<n_digits; i++)
        make_digit(digits[i], str+1+5*i, line_length);

    return str;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: mayan <number>\n");
        return 1;
    }
    int i = atoi(argv[1]);
    if (i <= 0) {
        fprintf(stderr, "number must be positive\n");
        return 1;
    }
    char *m = mayan(i);
    printf("%s",m);
    free(m);
    return 0;
}

const ONE: &str = "●";
const FIVE: &str = "——";
const ZERO: &str = "Θ";

fn main() {
    println!("{}", mayan(4005));
    println!("{}", mayan(8017));
    println!("{}", mayan(326_205));
    println!("{}", mayan(886_205));
    println!("{}", mayan(69));
    println!("{}", mayan(420));
    println!("{}", mayan(1_063_715_456));
}

fn mayan(dec: i64) -> String {
    let mut digits = vec![];
    let mut num = dec;
    while num > 0 {
        digits.push(num % 20);
        num /= 20;
    }
    digits = digits.into_iter().rev().collect();
    let mut boxes = vec!["".to_string(); 6];
    let n = digits.len();
    for (i, digit) in digits.iter().enumerate() {
        if i == 0 {
            boxes[0] = "┏━━━━".to_string();
            if i == n - 1 {
                boxes[0] += "┓";
            }
        } else if i == n - 1 {
            boxes[0] += "┳━━━━┓";
        } else {
            boxes[0] += "┳━━━━";
        }
        for j in 1..5 {
            boxes[j] += "┃";
            let elem = 0.max(digit - (4 - j as i64) * 5);
            if elem >= 5 {
                boxes[j] += &format!("{: ^4}", FIVE);
            } else if elem > 0 {
                boxes[j] += &format!("{: ^4}", ONE.repeat(elem as usize % 15));
            } else if j == 4 {
                boxes[j] += &format!("{: ^4}", ZERO);
            } else {
                boxes[j] += &"    ";
            }
            if i == n - 1 {
                boxes[j] += "┃";
            }
        }
        if i == 0 {
            boxes[5] = "┗━━━━".to_string();
            if i == n - 1 {
                boxes[5] += "┛";
            }
        } else if i == n - 1 {
            boxes[5] += "┻━━━━┛";
        } else {
            boxes[5] += "┻━━━━";
        }
    }

    let mut mayan = format!("Mayan {}:\n", dec);
    for b in boxes {
        mayan += &(b + "\n");
    }
    mayan
}


McNuggets problem

#include <stdio.h>

int
main() {
    int max = 0, i = 0, sixes, nines, twenties;

loopstart: while (i < 100) {
        for (sixes = 0; sixes*6 < i; sixes++) {
            if (sixes*6 == i) {
                i++;
                goto loopstart;
            }

            for (nines = 0; nines*9 < i; nines++) {
                if (sixes*6 + nines*9 == i) {
                    i++;
                    goto loopstart;
                }

                for (twenties = 0; twenties*20 < i; twenties++) {
                    if (sixes*6 + nines*9 + twenties*20 == i) {
                        i++;
                        goto loopstart;
                    }
                }
            }
        }
        max = i;
        i++;
    }

    printf("Maximum non-McNuggets number is %d\n", max);

    return 0;
}


Metaprogramming

#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]

#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)
#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)
#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)

COMPILE_TIME_ASSERT(sizeof(long)==8);
int main()
{
    COMPILE_TIME_ASSERT(sizeof(int)==4);
}

use std::ops::{Add, Mul, Sub};

macro_rules! assert_equal_len {

    ($a:ident, $b: ident, $func:ident, $op:tt) => (
        assert!($a.len() == $b.len(),
                "{:?}: dimension mismatch: {:?} {:?} {:?}",
                stringify!($func),
                ($a.len(),),
                stringify!($op),
                ($b.len(),));
    )
}

macro_rules! op {
    ($func:ident, $bound:ident, $op:tt, $method:ident) => (
        fn $func<T: $bound<T, Output=T> + Copy>(xs: &mut Vec<T>, ys: &Vec<T>) {
            assert_equal_len!(xs, ys, $func, $op);

            for (x, y) in xs.iter_mut().zip(ys.iter()) {
                *x = $bound::$method(*x, *y);

            }
        }
    )
}

op!(add_assign, Add, +=, add);
op!(mul_assign, Mul, *=, mul);
op!(sub_assign, Sub, -=, sub);

mod test {
    use std::iter;
    macro_rules! test {
        ($func: ident, $x:expr, $y:expr, $z:expr) => {
            #[test]
            fn $func() {
                for size in 0usize..10 {
                    let mut x: Vec<_> = iter::repeat($x).take(size).collect();
                    let y: Vec<_> = iter::repeat($y).take(size).collect();
                    let z: Vec<_> = iter::repeat($z).take(size).collect();

                    super::$func(&mut x, &y);

                    assert_eq!(x, z);
                }
            }
        }
    }

    test!(add_assign, 1u32, 2u32, 3u32);
    test!(mul_assign, 2u32, 3u32, 6u32);
    test!(sub_assign, 3u32, 2u32, 1u32);
}


Mind boggling card trick

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

#define SIM_N           5
#define PRINT_DISCARDED 1

#define min(x,y) ((x<y)?(x):(y))

typedef uint8_t card_t;

unsigned int rand_n(unsigned int n) {
    unsigned int out, mask = 1;

    while (mask < n) mask = mask<<1 | 1;

    do {
        out = rand() & mask;
    } while (out >= n);
    return out;
}

card_t rand_card() {
    return rand_n(52);
}

void print_card(card_t card) {
    static char *suits = "HCDS";
    static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    printf(" %s%c", cards[card>>2], suits[card&3]);
}

void shuffle(card_t *pack) {
    int card;
    card_t temp, randpos;
    for (card=0; card<52; card++) {
        randpos = rand_card();
        temp = pack[card];
        pack[card] = pack[randpos];
        pack[randpos] = temp;
    }
}

int trick() {
    card_t pack[52];
    card_t blacks[52/4], reds[52/4];
    card_t top, x, card;
    int blackn=0, redn=0, blacksw=0, redsw=0, result;

    for (card=0; card<52; card++) pack[card] = card;
    shuffle(pack);

#if PRINT_DISCARDED
    printf("Discarded:");
#endif
    for (card=0; card<52; card += 2) {
        top = pack[card];
        if (top & 1) {
            blacks[blackn++] = pack[card+1];
        } else {
            reds[redn++] = pack[card+1];
        }
#if PRINT_DISCARDED
        print_card(top);
#endif
    }
#if PRINT_DISCARDED
    printf("\n");
#endif

    x = rand_n(min(blackn, redn));
    for (card=0; card<x; card++) {

        blacksw = rand_n(blackn);
        redsw = rand_n(redn);

        top = blacks[blacksw];
        blacks[blacksw] = reds[redsw];
        reds[redsw] = top;
    }

    result = 0;
    for (card=0; card<blackn; card++)
        result += (blacks[card] & 1) == 1;
    for (card=0; card<redn; card++)
        result -= (reds[card] & 1) == 0;
    result = !result;

    printf("The number of black cards in the 'black' pile"
           " %s the number of red cards in the 'red' pile.\n",
           result? "equals" : "does not equal");
    return result;
}

int main() {
    unsigned int seed, i, successes = 0;
    FILE *r;

    if ((r = fopen("/dev/urandom", "r")) == NULL) {
        fprintf(stderr, "cannot open /dev/urandom\n");
        return 255;
    }
    if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
        fprintf(stderr, "failed to read from /dev/urandom\n");
        return 255;
    }
    fclose(r);
    srand(seed);

    for (i=1; i<=SIM_N; i++) {
        printf("Simulation %d\n", i);
        successes += trick();
        printf("\n");
    }

    printf("Result: %d successes out of %d simulations\n",
        successes, SIM_N);

    return 0;
}

extern crate rand;
use rand::Rng;
use std::iter::repeat;

#[derive(Debug, Eq, PartialEq, Clone)]
enum Colour {
    Black,
    Red,
}
use Colour::*;

fn main() {
    let mut rng = rand::thread_rng();

    let mut deck: Vec<_> = repeat(Black).take(26)
        .chain(repeat(Red).take(26))
        .collect();

    rng.shuffle(&mut deck);

    let mut black_stack = vec![];
    let mut red_stack = vec![];
    let mut discarded = vec![];

    print!("Discarding:");
    while let (Some(card), Some(next)) = (deck.pop(), deck.pop()) {
        print!(" {}", if card == Black { "B" } else { "R" });
        match card {
            Red => red_stack.push(next),
            Black => black_stack.push(next),
        }
        discarded.push(card);
    }
    println!();

    let max = red_stack.len().min(black_stack.len());
    let num = rng.gen_range(1, max);
    println!("Exchanging {} cards", num);

    for _ in 0..num {
        let red = rng.choose_mut(&mut red_stack).unwrap();
        let black = rng.choose_mut(&mut black_stack).unwrap();
        std::mem::swap(red, black);
    }

    let num_black = black_stack.iter()
        .filter(|&c| c == &Black)
        .count();
    let num_red = red_stack.iter()
        .filter(|&c| c == &Red)
        .count();

    println!("Number of black cards in black stack: {}", num_black);
    println!("Number of red cards in red stack: {}", num_red);
}


Modulinos

#[link(name = "scriptedmain")];

use std;

fn meaning_of_life() -> int {
	ret 42;
}

fn main() {
	std::io::println("Main: The meaning of life is " + core::int::to_str(meaning_of_life(), 10u));
}


Motzkin numbers

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

bool is_prime(uint64_t n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (uint64_t p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

int main() {
    setlocale(LC_ALL, "");
    printf(" n          M(n)             Prime?\n");
    printf("-----------------------------------\n");
    uint64_t m0 = 1, m1 = 1;
    for (uint64_t i = 0; i < 42; ++i) {
        uint64_t m =
            i > 1 ? (m1 * (2 * i + 1) + m0 * (3 * i - 3)) / (i + 2) : 1;
        printf("%2llu%'25llu  %s\n", i, m, is_prime(m) ? "true" : "false");
        m0 = m1;
        m1 = m;
    }
}

fn motzkin(n: usize) -> Vec<usize> {
    let mut m = vec![0; n];
    m[0] = 1;
    m[1] = 1;
    for i in 2..n {
        m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2);
    }
    m
}

fn main() {
    use num_format::{Locale, ToFormattedString};
    let count = 42;
    let m = motzkin(count);
    println!(" n          M(n)             Prime?");
    println!("-----------------------------------");
    for i in 0..count {
        println!(
            "{:2}  {:>23}  {}",
            i,
            m[i].to_formatted_string(&Locale::en),
            primal::is_prime(m[i] as u64)
        );
    }
}


Mutex

HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);

use std::{
    sync::{Arc, Mutex},
    thread,
    time::Duration,
};

fn main() {
    let shared = Arc::new(Mutex::new(String::new()));

    let handle1 = {
        let value = shared.clone();
        thread::spawn(move || {
            for _ in 0..20 {
                thread::sleep(Duration::from_millis(200));

                let mut guard = value.lock().unwrap();
                guard.push_str("A");
                println!("{}", guard);
            }
        })
    };

    let handle2 = {
        let value = shared.clone();
        thread::spawn(move || {
            for _ in 0..20 {
                thread::sleep(Duration::from_millis(300));

                {

                    let mut guard = value.lock().unwrap();
                    guard.push_str("B");
                    println!("{}", guard);
                }
            }
        })
    };

    handle1.join().ok();
    handle2.join().ok();
    shared.lock().ok().map_or((), |it| println!("Done: {}", it));
}


N-smooth numbers

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

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }
    return ptr;
}

void* xrealloc(void* p, size_t n) {
    void* ptr = realloc(p, n);
    if (ptr == NULL) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }
    return ptr;
}

bool is_prime(uint32_t n) {
    if (n == 2)
        return true;
    if (n < 2 || n % 2 == 0)
        return false;
    for (uint32_t p = 3; p * p <= n; p += 2) {
        if (n % p == 0)
            return false;
    }
    return true;
}

uint32_t find_primes(uint32_t from, uint32_t to, uint32_t** primes) {
    uint32_t count = 0, buffer_length = 16;
    uint32_t* buffer = xmalloc(sizeof(uint32_t) * buffer_length);
    for (uint32_t p = from; p <= to; ++p) {
        if (is_prime(p)) {
            if (count >= buffer_length) {
                uint32_t new_length = buffer_length * 2;
                if (new_length < count + 1)
                    new_length = count + 1;
                buffer = xrealloc(buffer, sizeof(uint32_t) * new_length);
                buffer_length = new_length;
            }
            buffer[count++] = p;
        }
    }
    *primes = buffer;
    return count;
}

void free_numbers(mpz_t* numbers, size_t count) {
    for (size_t i = 0; i < count; ++i)
        mpz_clear(numbers[i]);
    free(numbers);
}

mpz_t* find_nsmooth_numbers(uint32_t n, uint32_t count) {
    uint32_t* primes = NULL;
    uint32_t num_primes = find_primes(2, n, &primes);
    mpz_t* numbers = xmalloc(sizeof(mpz_t) * count);
    mpz_t* queue = xmalloc(sizeof(mpz_t) * num_primes);
    uint32_t* index = xmalloc(sizeof(uint32_t) * num_primes);
    for (uint32_t i = 0; i < num_primes; ++i) {
        index[i] = 0;
        mpz_init_set_ui(queue[i], primes[i]);
    }
    for (uint32_t i = 0; i < count; ++i)
        mpz_init(numbers[i]);
    mpz_set_ui(numbers[0], 1);
    for (uint32_t i = 1; i < count; ++i) {
        for (uint32_t p = 0; p < num_primes; ++p) {
            if (mpz_cmp(queue[p], numbers[i - 1]) == 0)
                mpz_mul_ui(queue[p], numbers[++index[p]], primes[p]);
        }
        uint32_t min_index = 0;
        for (uint32_t p = 1; p < num_primes; ++p) {
            if (mpz_cmp(queue[min_index], queue[p]) > 0)
                min_index = p;
        }
        mpz_set(numbers[i], queue[min_index]);
    }
    free_numbers(queue, num_primes);
    free(primes);
    free(index);
    return numbers;
}

void print_nsmooth_numbers(uint32_t n, uint32_t begin, uint32_t count) {
    uint32_t num = begin + count;
    mpz_t* numbers = find_nsmooth_numbers(n, num);
    printf("%u: ", n);
    mpz_out_str(stdout, 10, numbers[begin]);
    for (uint32_t i = 1; i < count; ++i) {
        printf(", ");
        mpz_out_str(stdout, 10, numbers[begin + i]);
    }
    printf("\n");
    free_numbers(numbers, num);
}

int main() {
    printf("First 25 n-smooth numbers for n = 2 -> 29:\n");
    for (uint32_t n = 2; n <= 29; ++n) {
        if (is_prime(n))
            print_nsmooth_numbers(n, 0, 25);
    }
    printf("\n3 n-smooth numbers starting from 3000th for n = 3 -> 29:\n");
    for (uint32_t n = 3; n <= 29; ++n) {
        if (is_prime(n))
            print_nsmooth_numbers(n, 2999, 3);
    }
    printf("\n20 n-smooth numbers starting from 30,000th for n = 503 -> 521:\n");
    for (uint32_t n = 503; n <= 521; ++n) {
        if (is_prime(n))
            print_nsmooth_numbers(n, 29999, 20);
    }
    return 0;
}

fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    let mut p = 5;
    while p * p <= n {
        if n % p == 0 {
            return false;
        }
        p += 2;
        if n % p == 0 {
            return false;
        }
        p += 4;
    }
    true
}

fn find_primes(from: u32, to: u32) -> Vec<u32> {
    let mut primes: Vec<u32> = Vec::new();
    for p in from..=to {
        if is_prime(p) {
            primes.push(p);
        }
    }
    primes
}

fn find_nsmooth_numbers(n: u32, count: usize) -> Vec<u128> {
    let primes = find_primes(2, n);
    let num_primes = primes.len();
    let mut result = Vec::with_capacity(count);
    let mut queue = Vec::with_capacity(num_primes);
    let mut index = Vec::with_capacity(num_primes);
    for i in 0..num_primes {
        index.push(0);
        queue.push(primes[i] as u128);
    }
    result.push(1);
    for i in 1..count {
        for p in 0..num_primes {
            if queue[p] == result[i - 1] {
                index[p] += 1;
                queue[p] = result[index[p]] * primes[p] as u128;
            }
        }
        let mut min_index: usize = 0;
        for p in 1..num_primes {
            if queue[min_index] > queue[p] {
                min_index = p;
            }
        }
        result.push(queue[min_index]);
    }
    result
}

fn print_nsmooth_numbers(n: u32, begin: usize, count: usize) {
    let numbers = find_nsmooth_numbers(n, begin + count);
    print!("{}: {}", n, &numbers[begin]);
    for i in 1..count {
        print!(", {}", &numbers[begin + i]);
    }
    println!();
}

fn main() {
    println!("First 25 n-smooth numbers for n = 2 -> 29:");
    for n in 2..=29 {
        if is_prime(n) {
            print_nsmooth_numbers(n, 0, 25);
        }
    }
    println!();
    println!("3 n-smooth numbers starting from 3000th for n = 3 -> 29:");
    for n in 3..=29 {
        if is_prime(n) {
            print_nsmooth_numbers(n, 2999, 3);
        }
    }
    println!();
    println!("20 n-smooth numbers starting from 30,000th for n = 503 -> 521:");
    for n in 503..=521 {
        if is_prime(n) {
            print_nsmooth_numbers(n, 29999, 20);
        }
    }
}


Next highest int from digits

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

void swap(char* str, int i, int j) {
    char c = str[i];
    str[i] = str[j];
    str[j] = c;
}

void reverse(char* str, int i, int j) {
    for (; i < j; ++i, --j)
        swap(str, i, j);
}

bool next_permutation(char* str) {
    int len = strlen(str);
    if (len < 2)
        return false;
    for (int i = len - 1; i > 0; ) {
        int j = i, k;
        if (str[--i] < str[j]) {
            k = len;
            while (str[i] >= str[--k]) {}
            swap(str, i, k);
            reverse(str, j, len - 1);
            return true;
        }
    }
    return false;
}

uint32_t next_highest_int(uint32_t n) {
    char str[16];
    snprintf(str, sizeof(str), "%u", n);
    if (!next_permutation(str))
        return 0;
    return strtoul(str, 0, 10);
}

int main() {
    uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};
    const int count = sizeof(numbers)/sizeof(int);
    for (int i = 0; i < count; ++i)
        printf("%d -> %d\n", numbers[i], next_highest_int(numbers[i]));

    const char big[] = "9589776899767587796600";
    char next[sizeof(big)];
    memcpy(next, big, sizeof(big));
    next_permutation(next);
    printf("%s -> %s\n", big, next);
    return 0;
}

fn next_permutation<T: PartialOrd>(array: &mut [T]) -> bool {
    let len = array.len();
    if len < 2 {
        return false;
    }
    let mut i = len - 1;
    while i > 0 {
        let j = i;
        i -= 1;
        if array[i] < array[j] {
            let mut k = len - 1;
            while array[i] >= array[k] {
                k -= 1;
            }
            array.swap(i, k);
            array[j..len].reverse();
            return true;
        }
    }
    false
}

fn next_highest_int(n: u128) -> u128 {
    use std::iter::FromIterator;
    let mut chars: Vec<char> = n.to_string().chars().collect();
    if !next_permutation(&mut chars) {
        return 0;
    }
    String::from_iter(chars).parse::<u128>().unwrap()
}

fn main() {
    for n in &[0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600] {
        println!("{} -> {}", n, next_highest_int(*n));
    }
}


Nice primes

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

bool is_prime(unsigned int n) {
    if (n < 2) {
        return false;
    }
    if (n % 2 == 0) {
        return n == 2;
    }
    if (n % 3 == 0) {
        return n == 3;
    }
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0) {
            return false;
        }
        p += 2;
        if (n % p == 0) {
            return false;
        }
    }
    return true;
}

unsigned int digital_root(unsigned int n) {
    return n == 0 ? 0 : 1 + (n - 1) % 9;
}

int main() {
    const unsigned int from = 500, to = 1000;
    unsigned int count = 0;
    unsigned int n;

    printf("Nice primes between %d and %d:\n", from, to);
    for (n = from; n < to; ++n) {
        if (is_prime(digital_root(n)) && is_prime(n)) {
            ++count;

            printf("%d", n);
            if (count % 10 == 0) {
                putc('\n', stdout);
            } else {
                putc(' ', stdout);
            }
        }
    }
    printf("\n%d nice primes found.\n", count);

    return 0;
}

fn digital_root(n: u64) -> u64 {
    if n == 0 {
        0
    } else {
        1 + (n - 1) % 9
    }
}

fn nice_primes(from: usize, to: usize) {
    primal::Sieve::new(to)
        .primes_from(from)
        .take_while(|x| *x < to)
        .filter(|x| primal::is_prime(digital_root(*x as u64)))
        .for_each(|x| println!("{}", x));
}

fn main() {
    nice_primes(500, 1000);
}


Nimber arithmetic

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

uint32_t hpo2(uint32_t n) {
    return n & -n;
}

uint32_t lhpo2(uint32_t n) {
    uint32_t q = 0, m = hpo2(n);
    for (; m % 2 == 0; m >>= 1, ++q) {}
    return q;
}

uint32_t nimsum(uint32_t x, uint32_t y) {
    return x ^ y;
}

uint32_t nimprod(uint32_t x, uint32_t y) {
    if (x < 2 || y < 2)
        return x * y;
    uint32_t h = hpo2(x);
    if (x > h)
        return nimprod(h, y) ^ nimprod(x ^ h, y);
    if (hpo2(y) < y)
        return nimprod(y, x);
    uint32_t xp = lhpo2(x), yp = lhpo2(y);
    uint32_t comp = xp & yp;
    if (comp == 0)
        return x * y;
    h = hpo2(comp);
    return nimprod(nimprod(x >> h, y >> h), 3 << (h - 1));
}

void print_table(uint32_t n, char op, uint32_t(*func)(uint32_t, uint32_t)) {
    printf(" %c |", op);
    for (uint32_t a = 0; a <= n; ++a)
        printf("%3d", a);
    printf("\n--- -");
    for (uint32_t a = 0; a <= n; ++a)
        printf("---");
    printf("\n");
    for (uint32_t b = 0; b <= n; ++b) {
        printf("%2d |", b);
        for (uint32_t a = 0; a <= n; ++a)
            printf("%3d", func(a, b));
        printf("\n");
    }
}

int main() {
    print_table(15, '+', nimsum);
    printf("\n");
    print_table(15, '*', nimprod);
    const uint32_t a = 21508, b = 42689;
    printf("\n%d + %d = %d\n", a, b, nimsum(a, b));
    printf("%d * %d = %d\n", a, b, nimprod(a, b));
    return 0;
}

fn hpo2(n: u32) -> u32 {
    n & (0xFFFFFFFF - n + 1)
}

fn lhpo2(n: u32) -> u32 {
    let mut q: u32 = 0;
    let mut m: u32 = hpo2(n);
    while m % 2 == 0 {
        m >>= 1;
        q += 1;
    }
    q
}

fn nimsum(x: u32, y: u32) -> u32 {
    x ^ y
}

fn nimprod(x: u32, y: u32) -> u32 {
    if x < 2 || y < 2 {
        return x * y;
    }
    let mut h: u32 = hpo2(x);
    if x > h {
        return nimprod(h, y) ^ nimprod(x ^ h, y);
    }
    if hpo2(y) < y {
        return nimprod(y, x);
    }
    let xp: u32 = lhpo2(x);
    let yp: u32 = lhpo2(y);
    let comp: u32 = xp & yp;
    if comp == 0 {
        return x * y;
    }
    h = hpo2(comp);
    nimprod(nimprod(x >> h, y >> h), 3 << (h - 1))
}

fn print_table(n: u32, op: char, func: fn(u32, u32) -> u32) {
    print!(" {} |", op);
    for a in 0..=n {
        print!("{:3}", a);
    }
    print!("\n--- -");
    for _ in 0..=n {
        print!("---");
    }
    println!();
    for b in 0..=n {
        print!("{:2} |", b);
        for a in 0..=n {
            print!("{:3}", func(a, b));
        }
        println!();
    }
}

fn main() {
    print_table(15, '+', nimsum);
    println!();
    print_table(15, '*', nimprod);
    let a: u32 = 21508;
    let b: u32 = 42689;
    println!("\n{} + {} = {}", a, b, nimsum(a, b));
    println!("{} * {} = {}", a, b, nimprod(a, b));
}


Nonoblock

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

void nb(int cells, int total_block_size, int* blocks, int block_count,
        char* output, int offset, int* count) {
    if (block_count == 0) {
        printf("%2d  %s\n", ++*count, output);
        return;
    }
    int block_size = blocks[0];
    int max_pos = cells - (total_block_size + block_count - 1);
    total_block_size -= block_size;
    cells -= block_size + 1;
    ++blocks;
    --block_count;
    for (int i = 0; i <= max_pos; ++i, --cells) {
        memset(output + offset, '.', max_pos + block_size);
        memset(output + offset + i, '#', block_size);
        nb(cells, total_block_size, blocks, block_count, output,
           offset + block_size + i + 1, count);
    }
}

void nonoblock(int cells, int* blocks, int block_count) {
    printf("%d cells and blocks [", cells);
    for (int i = 0; i < block_count; ++i)
        printf(i == 0 ? "%d" : ", %d", blocks[i]);
    printf("]:\n");
    int total_block_size = 0;
    for (int i = 0; i < block_count; ++i)
        total_block_size += blocks[i];
    if (cells < total_block_size + block_count - 1) {
        printf("no solution\n");
        return;
    }
    char output[cells + 1];
    memset(output, '.', cells);
    output[cells] = '\0';
    int count = 0;
    nb(cells, total_block_size, blocks, block_count, output, 0, &count);
}

int main() {
    int blocks1[] = {2, 1};
    nonoblock(5, blocks1, 2);
    printf("\n");

    nonoblock(5, NULL, 0);
    printf("\n");

    int blocks2[] = {8};
    nonoblock(10, blocks2, 1);
    printf("\n");

    int blocks3[] = {2, 3, 2, 3};
    nonoblock(15, blocks3, 4);
    printf("\n");

    int blocks4[] = {2, 3};
    nonoblock(5, blocks4, 2);

    return 0;
}

struct Nonoblock {
  width: usize,
  config: Vec<usize>,
  spaces: Vec<usize>,
}

impl Nonoblock {
  pub fn new(width: usize, config: Vec<usize>) -> Nonoblock {
    Nonoblock {
      width: width,
      config: config,
      spaces: Vec::new(),
    }
  }

  pub fn solve(&mut self) -> Vec<Vec<i32>> {
    let mut output: Vec<Vec<i32>> = Vec::new();
    self.spaces = (0..self.config.len()).fold(Vec::new(), |mut s, i| {
      s.push(match i {
        0 => 0,
        _ => 1,
      });
      s
    });
    if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() <= self.width {
      'finished: loop {
        match self.spaces.iter().enumerate().fold((0, vec![0; self.width]), |mut a, (i, s)| {
            (0..self.config[i]).for_each(|j| a.1[a.0 + j + *s] = 1 + i as i32);
            return (a.0 + self.config[i] + *s, a.1);
          }) {
          (_, out) => output.push(out),
        }
        let mut i: usize = 1;
        'calc: loop {
          let len = self.spaces.len();
          if i > len {
            break 'finished;
          } else {
            self.spaces[len - i] += 1
          }
          if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() > self.width {
            self.spaces[len - i] = 1;
            i += 1;
          } else {
            break 'calc;
          }
        }
      }
    }
    output
  }
}

fn main() {
  let mut blocks = [
    Nonoblock::new(5, vec![2, 1]),
    Nonoblock::new(5, vec![]),
    Nonoblock::new(10, vec![8]),
    Nonoblock::new(15, vec![2, 3, 2, 3]),
    Nonoblock::new(5, vec![2, 3]),
  ];

  for block in blocks.iter_mut() {
    println!("{} cells and {:?} blocks", block.width, block.config);
    println!("{}",(0..block.width).fold(String::from("="), |a, _| a + "=="));
    let solutions = block.solve();
    if solutions.len() > 0 {
      for solution in solutions.iter() {
        println!("{}", solution.iter().fold(String::from("|"), |s, f| s + &match f {
          i if *i > 0 => (('A' as u8 + ((*i - 1) as u8) % 26) as char).to_string(),
          _ => String::from("_"),
        }+ "|"));
      }
    } else {
      println!("No solutions. ");
    }
    println!();
  }
}


Numbers divisible by their individual digits, but not by the product of their digits.

#include <stdio.h>

int divisible(int n) {
    int p = 1;
    int c, d;

    for (c=n; c; c /= 10) {
        d = c % 10;
        if (!d || n % d) return 0;
        p *= d;
    }

    return n % p;
}

int main() {
    int n, c=0;

    for (n=1; n<1000; n++) {
        if (divisible(n)) {
            printf("%5d", n);
            if (!(++c % 10)) printf("\n");
        }
    }
    printf("\n");

    return 0;
}

fn to_digits( n : i32 ) -> Vec<i32> {
   let mut i : i32 = n ;
   let mut digits : Vec<i32> = Vec::new( ) ;
   while i != 0 {
      digits.push( i % 10 ) ;
      i /= 10 ;
   }
   digits
}

fn my_condition( num : i32 ) -> bool {
   let digits : Vec<i32> = to_digits( num ) ;
   if ! digits.iter( ).any( | x | *x == 0 ) {
      let prod : i32 = digits.iter( ).product( ) ;
      return digits.iter( ).all( | x | num % x == 0 ) &&
         num % prod != 0 ;
   }
   else {
      false
   }
}

fn main() {
let mut count : i32 = 0 ;
   for n in 10 .. 1000 {
      if my_condition( n ) {
         print!("{:5}" , n) ;
         count += 1 ;
         if count % 10 == 0 {
            println!( ) ;
         }
      }
   }
   println!();
}


Old Russian measure of length

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

#define UNITS_LENGTH 13

int main(int argC,char* argV[])
{
	int i,reference;
	char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
    double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};

	if(argC!=3)
		printf("Usage : %s followed by length as <value> <unit>");
	else{
		for(i=0;argV[2][i]!=00;i++)
			argV[2][i] = tolower(argV[2][i]);

		for(i=0;i<UNITS_LENGTH;i++){
			if(strstr(argV[2],units[i])!=NULL){
				reference = i;
				factor = atof(argV[1])*values[i];
				break;
			}
		}

		printf("%s %s is equal in length to : \n",argV[1],argV[2]);

		for(i=0;i<UNITS_LENGTH;i++){
			if(i!=reference)
				printf("\n%lf %s",factor/values[i],units[i]);
		}
	}

	return 0;
}

use std::env;
use std::process;
use std::collections::HashMap;

fn main() {

	let units: HashMap<&str, f32> = [("arshin",0.7112),("centimeter",0.01),("diuym",0.0254),("fut",0.3048),("kilometer",1000.0),("liniya",0.00254),("meter",1.0),("milia",7467.6),("piad",0.1778),("sazhen",2.1336),("tochka",0.000254),("vershok",0.04445),("versta",1066.8)].iter().cloned().collect();

	let args: Vec<String> = env::args().collect();
	if args.len() < 3 {
		eprintln!("A correct use is oldrus [amount] [unit].");
		process::exit(1);
	};

	let length_float;
	length_float = match args[1].parse::<f32>() {
		Ok(length_float) =>  length_float,
		Err(..) => 1 as f32,
	};

	let unit: &str = &args[2];
	if ! units.contains_key(unit) {
		let mut keys: Vec<&str> = Vec::new();
		for i in units.keys() {
			keys.push(i)
		};
		eprintln!("The correct units are: {}.", keys.join(", "));
		process::exit(1);
	};

	println!("{} {} to:", length_float, unit);
	for (lunit, length) in &units {
		println!("	{}: {:?}", lunit,  length_float * units.get(unit).unwrap() / length);
	};

}


Optional parameters

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

typedef const char * String;
typedef struct sTable {
    String * *rows;
    int      n_rows,n_cols;
} *Table;

typedef int (*CompareFctn)(String a, String b);

struct {
   CompareFctn  compare;
   int   column;
   int   reversed;
} sortSpec;

int CmprRows( const void *aa, const void *bb)
{
   String *rA = *(String *const *)aa;
   String *rB = *(String *const *)bb;
   int sortCol = sortSpec.column;

   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];
   String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];
   return sortSpec.compare( left, right );
}

int sortTable(Table tbl, const char* argSpec,... )
{
   va_list vl;
   const char *p;
   int c;
   sortSpec.compare = &strcmp;
   sortSpec.column = 0;
   sortSpec.reversed = 0;

   va_start(vl, argSpec);
   if (argSpec)
      for (p=argSpec; *p; p++) {
         switch (*p) {
         case 'o':
            sortSpec.compare = va_arg(vl,CompareFctn);
            break;
         case 'c':
            c = va_arg(vl,int);
            if ( 0<=c && c<tbl->n_cols)
               sortSpec.column  = c;
            break;
         case 'r':
            sortSpec.reversed = (0!=va_arg(vl,int));
            break;
         }
      }
   va_end(vl);
   qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);
   return 0;
}

void printTable( Table tbl, FILE *fout, const char *colFmts[])
{
   int row, col;

   for (row=0; row<tbl->n_rows; row++) {
      fprintf(fout, "   ");
      for(col=0; col<tbl->n_cols; col++) {
         fprintf(fout, colFmts[col], tbl->rows[row][col]);
      }
      fprintf(fout, "\n");
   }
   fprintf(fout, "\n");
}

int ord(char v)
{
    return v-'0';
}

int cmprStrgs(String s1, String s2)
{
    const char *p1 = s1;
    const char *p2 = s2;
    const char *mrk1, *mrk2;
    while ((tolower(*p1) == tolower(*p2)) && *p1) {
       p1++; p2++;
    }
    if (isdigit(*p1) && isdigit(*p2)) {
        long v1, v2;
        if ((*p1 == '0') ||(*p2 == '0')) {
            while (p1 > s1) {
                p1--; p2--;
                if (*p1 != '0') break;
            }
            if (!isdigit(*p1)) {
                p1++; p2++;
            }
        }
        mrk1 = p1; mrk2 = p2;
        v1 = 0;
        while(isdigit(*p1)) {
            v1 = 10*v1+ord(*p1);
            p1++;
        }
        v2 = 0;
        while(isdigit(*p2)) {
            v2 = 10*v2+ord(*p2);
            p2++;
        }
        if (v1 == v2)
           return(p2-mrk2)-(p1-mrk1);
        return v1 - v2;
    }
    if (tolower(*p1) != tolower(*p2))
       return (tolower(*p1) - tolower(*p2));
    for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);
    return (*p1 -*p2);
}

int main()
{
   const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"};
   String r1[] = { "a101", "red",  "Java" };
   String r2[] = { "ab40", "gren", "Smalltalk" };
   String r3[] = { "ab9",  "blue", "Fortran" };
   String r4[] = { "ab09", "ylow", "Python" };
   String r5[] = { "ab1a", "blak", "Factor" };
   String r6[] = { "ab1b", "brwn", "C Sharp" };
   String r7[] = { "Ab1b", "pink", "Ruby" };
   String r8[] = { "ab1",  "orng", "Scheme" };

   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };
   struct sTable table;
   table.rows = rows;
   table.n_rows = 8;
   table.n_cols = 3;

   sortTable(&table, "");
   printf("sort on col 0, ascending\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "ro", 1, &cmprStrgs);
   printf("sort on col 0, reverse.special\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "c", 1);
   printf("sort on col 1, ascending\n");
   printTable(&table, stdout, colFmts);

   sortTable(&table, "cr", 2, 1);
   printf("sort on col 2, reverse\n");
   printTable(&table, stdout, colFmts);
   return 0;
}

use std::cmp::Ordering;

struct Table {
    rows: Vec<Vec<String>>,
    ordering_function: fn(&str, &str) -> Ordering,
    ordering_column: usize,
    reverse: bool,
}

impl Table {
    fn new(rows: Vec<Vec<String>>) -> Table {
        Table {
            rows: rows,
            ordering_column: 0,
            reverse: false,
            ordering_function: |str1, str2| str1.cmp(str2),
        }
    }
}

impl Table {
    fn with_ordering_column(&mut self, ordering_column: usize) -> &mut Table {
        self.ordering_column = ordering_column;
        self
    }

    fn with_reverse(&mut self, reverse: bool) -> &mut Table {
        self.reverse = reverse;
        self
    }

    fn with_ordering_fun(&mut self, compare: fn(&str, &str) -> Ordering) -> &mut Table {
        self.ordering_function = compare;
        self
    }

    fn sort(&mut self) {
        let fun = &mut self.ordering_function;
        let idx = self.ordering_column;
        if self.reverse {
            self.rows
                .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]).reverse());
        } else {
            self.rows
                .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]));
        }
    }
}

#[cfg(test)]
mod test {
    use super::Table;

    fn generate_test_table() -> Table {
        Table::new(vec![
            vec!["0".to_string(), "fff".to_string()],
            vec!["2".to_string(), "aab".to_string()],
            vec!["1".to_string(), "ccc".to_string()],
        ])
    }

    #[test]
    fn test_simple_sort() {
        let mut table = generate_test_table();
        table.sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["0".to_string(), "fff".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["2".to_string(), "aab".to_string()],
            ],
        )
    }

    #[test]
    fn test_ordering_column() {
        let mut table = generate_test_table();
        table.with_ordering_column(1).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_with_reverse() {
        let mut table = generate_test_table();
        table.with_reverse(true).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_custom_ordering_fun() {
        let mut table = generate_test_table();

        table.with_ordering_fun(|x, y| x.cmp(y).reverse()).sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }

    #[test]
    fn test_everything_together() {
        let mut table = generate_test_table();

        table
            .with_ordering_fun(|x, y| x.cmp(y).reverse())
            .with_reverse(true)
            .with_ordering_column(1)
            .sort();
        assert_eq!(
            table.rows,
            vec![
                vec!["2".to_string(), "aab".to_string()],
                vec!["1".to_string(), "ccc".to_string()],
                vec!["0".to_string(), "fff".to_string()],
            ],
        )
    }
}


Ormiston pairs

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

bool *sieve(int limit) {
    int i, p;
    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;
        }
    }
    return c;
}

typedef struct {
    char digs[20];
    int count;
} digits;

digits getDigits(int n) {
    if (n == 0) return (digits){ {0}, 1 };
    digits d;
    d.count = 0;
    while (n > 0) {
        d.digs[d.count++] = n % 10;
        n = n / 10;
    }
    return d;
}

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

int main() {
    const int limit = 1000000000;
    int i, j, k, pc = 0, count = 0, count2 = 0, p1, p2, key1, key2;
    digits d;
    bool *c = sieve(limit);
    for (i = 0; i < limit; ++i) {
        if (!c[i]) ++pc;
    }
    int *primes = (int *)malloc(pc * sizeof(int));
    for (i = 0, j = 0; i < limit; ++i) {
        if (!c[i]) primes[j++] = i;
    }
    pair orm30[30];
    int counts[5];
    j = 100000;
    for (i = 0; i < pc-1; ++i) {
        p1 = primes[i];
        p2 = primes[i+1];
        if ((p2 - p1) % 18) continue;
        key1 = 1;
        d = getDigits(p1);
        for (k = 0; k < d.count; ++k) key1 *= primes[d.digs[k]];
        key2 = 1;
        d = getDigits(p2);
        for (k = 0; k < d.count; ++k) key2 *= primes[d.digs[k]];
        if (key1 == key2) {
            if (count < 30) orm30[count] = (pair){p1, p2};
            if (p1 >= j) {
                counts[count2++] = count;
                j *= 10;
            }
            ++count;
        }
    }
    counts[count2] = count;
    printf("First 30 Ormiston pairs:\n");
    setlocale(LC_NUMERIC, "");
    for (i = 0; i < 30; ++i) {
        printf("[%'6d, %'6d] ", orm30[i].x, orm30[i].y);
        if (!((i+1) % 3)) printf("\n");
    }
    printf("\n");
    j = 100000;
    for (i = 0; i < 5; ++i) {
        printf("%'d Ormiston pairs before %'d\n", counts[i], j);
        j *= 10;
    }
    free(c);
    free(primes);
    return 0;
}

fn get_digits(mut n: usize) -> [usize; 10] {
    let mut digits = [0; 10];
    while n > 0 {
        digits[n % 10] += 1;
        n /= 10;
    }
    digits
}

fn ormiston_pairs() -> impl std::iter::Iterator<Item = (usize, usize)> {
    let mut digits = [0; 10];
    let mut prime = 0;
    let mut primes = primal::Primes::all();
    std::iter::from_fn(move || {
        for p in primes.by_ref() {
            let prime0 = prime;
            prime = p;
            let digits0 = digits;
            digits = get_digits(prime);
            if digits == digits0 {
                return Some((prime0, prime));
            }
        }
        None
    })
}

fn main() {
    let mut count = 0;
    let mut op = ormiston_pairs();
    println!("First 30 Ormiston pairs:");
    for (p1, p2) in op.by_ref() {
        count += 1;
        let c = if count % 3 == 0 { '\n' } else { ' ' };
        print!("({:5}, {:5}){}", p1, p2, c);
        if count == 30 {
            break;
        }
    }
    println!();
    let mut limit = 1000000;
    for (p1, _) in op.by_ref() {
        if p1 > limit {
            println!("Number of Ormiston pairs < {}: {}", limit, count);
            limit *= 10;
            if limit == 10000000000 {
                break;
            }
        }
        count += 1;
    }
}


Padovan n-step number sequences

#include <stdio.h>

void padovanN(int n, size_t t, int *p) {
    int i, j;
    if (n < 2 || t < 3) {
        for (i = 0; i < t; ++i) p[i] = 1;
        return;
    }
    padovanN(n-1, t, p);
    for (i = n + 1; i < t; ++i) {
        p[i] = 0;
        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
    }
}

int main() {
    int n, i;
    const size_t t = 15;
    int p[t];
    printf("First %ld terms of the Padovan n-step number sequences:\n", t);
    for (n = 2; n <= 8; ++n) {
        for (i = 0; i < t; ++i) p[i] = 0;
        padovanN(n, t, p);
        printf("%d: ", n);
        for (i = 0; i < t; ++i) printf("%3d ", p[i]);
        printf("\n");
    }
    return 0;
}


Padovan sequence

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

int pRec(int n) {
    static int *memo = NULL;
    static size_t curSize = 0;

    if (curSize <= (size_t) n) {
        size_t lastSize = curSize;
        while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
        memo = realloc(memo, curSize * sizeof(int));
        memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
    }

    if (memo[n] == 0) {
        if (n<=2) memo[n] = 1;
        else memo[n] = pRec(n-2) + pRec(n-3);
    }

    return memo[n];
}

int pFloor(int n) {
    long double p = 1.324717957244746025960908854;
    long double s = 1.0453567932525329623;
    return powl(p, n-1)/s + 0.5;
}

void nextLSystem(const char *prev, char *buf) {
    while (*prev) {
        switch (*prev++) {
            case 'A': *buf++ = 'B'; break;
            case 'B': *buf++ = 'C'; break;
            case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
        }
    }
    *buf = '\0';
}

int main() {

    #define BUFSZ 8192
    char buf1[BUFSZ], buf2[BUFSZ];
    int i;

    printf("P_0 .. P_19: ");
    for (i=0; i<20; i++) printf("%d ", pRec(i));
    printf("\n");

    printf("The floor- and recurrence-based functions ");
    for (i=0; i<64; i++) {
        if (pRec(i) != pFloor(i)) {
            printf("do not match at %d: %d != %d.\n",
                i, pRec(i), pFloor(i));
            break;
        }
    }
    if (i == 64) {
        printf("match from P_0 to P_63.\n");
    }

    printf("\nThe first 10 L-system strings are:\n");
    for (strcpy(buf1, "A"), i=0; i<10; i++) {
        printf("%s\n", buf1);
        strcpy(buf2, buf1);
        nextLSystem(buf2, buf1);
    }

    printf("\nThe floor- and L-system-based functions ");
    for (strcpy(buf1, "A"), i=0; i<32; i++) {
        if ((int)strlen(buf1) != pFloor(i)) {
            printf("do not match at %d: %d != %d\n",
                i, (int)strlen(buf1), pFloor(i));
            break;
        }
        strcpy(buf2, buf1);
        nextLSystem(buf2, buf1);
    }
    if (i == 32) {
        printf("match from P_0 to P_31.\n");
    }

    return 0;
}

fn padovan_recur() -> impl std::iter::Iterator<Item = usize> {
    let mut p = vec![1, 1, 1];
    let mut n = 0;
    std::iter::from_fn(move || {
        let pn = if n < 3 { p[n] } else { p[0] + p[1] };
        p[0] = p[1];
        p[1] = p[2];
        p[2] = pn;
        n += 1;
        Some(pn)
    })
}

fn padovan_floor() -> impl std::iter::Iterator<Item = usize> {
    const P: f64 = 1.324717957244746025960908854;
    const S: f64 = 1.0453567932525329623;
    (0..).map(|x| (P.powf((x - 1) as f64) / S + 0.5).floor() as usize)
}

fn padovan_lsystem() -> impl std::iter::Iterator<Item = String> {
    let mut str = String::from("A");
    std::iter::from_fn(move || {
        let result = str.clone();
        let mut next = String::new();
        for ch in str.chars() {
            match ch {
                'A' => next.push('B'),
                'B' => next.push('C'),
                _ => next.push_str("AB"),
            }
        }
        str = next;
        Some(result)
    })
}

fn main() {
    println!("First 20 terms of the Padovan sequence:");
    for p in padovan_recur().take(20) {
        print!("{} ", p);
    }
    println!();

    println!(
        "\nRecurrence and floor functions agree for first 64 terms? {}",
        padovan_recur().take(64).eq(padovan_floor().take(64))
    );

    println!("\nFirst 10 strings produced from the L-system:");
    for p in padovan_lsystem().take(10) {
        print!("{} ", p);
    }
    println!();

    println!(
        "\nLength of first 32 strings produced from the L-system = Padovan sequence? {}",
        padovan_lsystem()
            .map(|x| x.len())
            .take(32)
            .eq(padovan_recur().take(32))
    );
}


Palindromic gapful numbers

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

typedef uint64_t integer;

integer reverse(integer n) {
    integer rev = 0;
    while (n > 0) {
        rev = rev * 10 + (n % 10);
        n /= 10;
    }
    return rev;
}

typedef struct palgen_tag {
    integer power;
    integer next;
    int digit;
    bool even;
} palgen_t;

void init_palgen(palgen_t* palgen, int digit) {
    palgen->power = 10;
    palgen->next = digit * palgen->power - 1;
    palgen->digit = digit;
    palgen->even = false;
}

integer next_palindrome(palgen_t* p) {
    ++p->next;
    if (p->next == p->power * (p->digit + 1)) {
        if (p->even)
            p->power *= 10;
        p->next = p->digit * p->power;
        p->even = !p->even;
    }
    return p->next * (p->even ? 10 * p->power : p->power)
        + reverse(p->even ? p->next : p->next/10);
}

bool gapful(integer n) {
    integer m = n;
    while (m >= 10)
        m /= 10;
    return n % (n % 10 + 10 * m) == 0;
}

void print(int len, integer array[][len]) {
    for (int digit = 1; digit < 10; ++digit) {
        printf("%d: ", digit);
        for (int i = 0; i < len; ++i)
            printf(" %llu", array[digit - 1][i]);
        printf("\n");
    }
}

int main() {
    const int n1 = 20, n2 = 15, n3 = 10;
    const int m1 = 100, m2 = 1000;

    integer pg1[9][n1];
    integer pg2[9][n2];
    integer pg3[9][n3];

    for (int digit = 1; digit < 10; ++digit) {
        palgen_t pgen;
        init_palgen(&pgen, digit);
        for (int i = 0; i < m2; ) {
            integer n = next_palindrome(&pgen);
            if (!gapful(n))
                continue;
            if (i < n1)
                pg1[digit - 1][i] = n;
            else if (i < m1 && i >= m1 - n2)
                pg2[digit - 1][i - (m1 - n2)] = n;
            else if (i >= m2 - n3)
                pg3[digit - 1][i - (m2 - n3)] = n;
            ++i;
        }
    }

    printf("First %d palindromic gapful numbers ending in:\n", n1);
    print(n1, pg1);

    printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1);
    print(n2, pg2);

    printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2);
    print(n3, pg3);

    return 0;
}

fn palindromicgapfuls(digit: u64, count: u64, keep: usize) -> Vec<u64> {
  let mut palcnt = 0u64;
  let to_skip = count - keep as u64;
  let mut gapfuls: Vec<u64> = vec![];
  let nn = digit * 11;
  let (mut power, mut base) = (1, 1u64);
  loop { power += 1;
    if power & 1 == 0 { base *= 10 };
    let base11  = base * 11;
    let this_lo = base * digit;
    let next_lo = base * (digit + 1);
    for front_half in (this_lo..next_lo-1).step_by(10) {
      let (mut left_half, mut basep) = (front_half.to_string(), 0);
      let right_half = left_half.chars().rev().collect::<String>();
      if power & 1 == 1 { basep = base11; left_half.push_str(&right_half) }
      else              { basep = base;   left_half.pop(); left_half.push_str(&right_half) };
      let mut palindrome = left_half.parse::<u64>().unwrap();
      for _ in 0..10 {
        if palindrome % nn == 0 { palcnt += 1; if palcnt > to_skip { gapfuls.push(palindrome) } };
        palindrome += basep;
      }
      if gapfuls.len() >= keep { return gapfuls[0..keep].to_vec() };
    }
  }
}

fn main() {
  let t = std::time::Instant::now();

  let (count, keep) = (20, 20);
  println!("First 20 palindromic gapful numbers ending with:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  let (count, keep) = (100, 15);
  println!("\nLast 15 of first 100 palindromic gapful numbers ending in:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  let (count, keep) = (1_000, 10);
  println!("\nLast 10 of first 1000 palindromic gapful numbers ending in:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  let (count, keep) = (100_000, 1);
  println!("\n100,000th palindromic gapful number ending with:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  let (count, keep) = (1_000_000, 1);
  println!("\n1,000,000th palindromic gapful number ending with:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  let (count, keep) = (10_000_000, 1);
  println!("\n10,000,000th palindromic gapful number ending with:");
  for digit in 1..10 { println!("{} : {:?}", digit, palindromicgapfuls(digit, count, keep)); }

  println!("{:?}", t.elapsed())
}


Parse an IP Address

#include <string.h>
#include <memory.h>

static unsigned int _parseDecimal ( const char** pchCursor )
{
    unsigned int nVal = 0;
    char chNow;
    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
    {

        nVal *= 10;
        nVal += chNow - '0';

        ++*pchCursor;
    }
    return nVal;
}

static unsigned int _parseHex ( const char** pchCursor )
{
    unsigned int nVal = 0;
    char chNow;
    while ( chNow = **pchCursor & 0x5f,
            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
            (chNow >= 'A' && chNow <= 'F')
            )
    {
        unsigned char nybbleValue;
        chNow -= 0x10;
        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );

        nVal <<= 4;
        nVal += nybbleValue;

        ++*pchCursor;
    }
    return nVal;
}

int ParseIPv4OrIPv6 ( const char** ppszText,
        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
    unsigned char* abyAddrLocal;
    unsigned char abyDummyAddr[16];

    const char* pchColon = strchr ( *ppszText, ':' );
    const char* pchDot = strchr ( *ppszText, '.' );
    const char* pchOpenBracket = strchr ( *ppszText, '[' );
    const char* pchCloseBracket = NULL;

    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );

    if ( bIsIPv6local )
    {

        pchCloseBracket = strchr ( *ppszText, ']' );
        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
                pchCloseBracket < pchOpenBracket ) )
            return 0;
    }
    else
    {

        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
            return 0;
    }

    if ( NULL != pbIsIPv6 )
        *pbIsIPv6 = bIsIPv6local;

    abyAddrLocal = abyAddr;
    if ( NULL == abyAddrLocal )
        abyAddrLocal = abyDummyAddr;

    if ( ! bIsIPv6local )
    {

        unsigned char* pbyAddrCursor = abyAddrLocal;
        unsigned int nVal;
        const char* pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;
        ++(*ppszText);

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;
        ++(*ppszText);

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;
        ++(*ppszText);

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );
        if ( nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;

        if ( ':' == **ppszText && NULL != pnPort )
        {
            unsigned short usPortNetwork;
            ++(*ppszText);
            pszTextBefore = *ppszText;
            nVal =_parseDecimal ( ppszText );
            if ( nVal > 65535 || pszTextBefore == *ppszText )
                return 0;
            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
            *pnPort = usPortNetwork;
            return 1;
        }
        else
        {
            if ( NULL != pnPort )
                *pnPort = 0;
            return 1;
        }
    }
    else
    {
        unsigned char* pbyAddrCursor;
        unsigned char* pbyZerosLoc;
        int bIPv4Detected;
        int nIdx;

        if ( NULL != pchOpenBracket )
            *ppszText = pchOpenBracket + 1;
        pbyAddrCursor = abyAddrLocal;
        pbyZerosLoc = NULL;
        bIPv4Detected = 0;
        for ( nIdx = 0; nIdx < 8; ++nIdx )
        {
            const char* pszTextBefore = *ppszText;
            unsigned nVal =_parseHex ( ppszText );
            if ( pszTextBefore == *ppszText )
            {
                if ( NULL != pbyZerosLoc )
                {

                    if ( pbyZerosLoc == pbyAddrCursor )
                    {
                        --nIdx;
                        break;
                    }
                    return 0;
                }
                if ( ':' != **ppszText )
                    return 0;
                if ( 0 == nIdx )
                {
                    ++(*ppszText);
                    if ( ':' != **ppszText )
                        return 0;
                }

                pbyZerosLoc = pbyAddrCursor;
                ++(*ppszText);
            }
            else
            {
                if ( '.' == **ppszText )
                {

                    const char* pszTextlocal = pszTextBefore;
                    unsigned char abyAddrlocal[16];
                    int bIsIPv6local;
                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
                    *ppszText = pszTextlocal;
                    if ( ! bParseResultlocal || bIsIPv6local )
                        return 0;

                    *(pbyAddrCursor++) = abyAddrlocal[0];
                    *(pbyAddrCursor++) = abyAddrlocal[1];
                    *(pbyAddrCursor++) = abyAddrlocal[2];
                    *(pbyAddrCursor++) = abyAddrlocal[3];
                    ++nIdx;
                    bIPv4Detected = 1;
                    break;
                }

                if ( nVal > 65535 )
                    return 0;
                *(pbyAddrCursor++) = nVal >> 8;
                *(pbyAddrCursor++) = nVal & 0xff;
                if ( ':' == **ppszText )
                {
                    ++(*ppszText);
                }
                else
                {
                    break;
                }
            }
        }

        if ( NULL != pbyZerosLoc )
        {
            int nHead = (int)( pbyZerosLoc - abyAddrLocal );
            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
            int nZeros = 16 - nTail - nHead;
            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
            memset ( pbyZerosLoc, 0, nZeros );
        }

        if ( bIPv4Detected )
        {
            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
                return 0;
        }

        if ( NULL != pchOpenBracket )
        {
            if ( ']' != **ppszText )
                return 0;
            ++(*ppszText);
        }

        if ( ':' == **ppszText && NULL != pnPort )
        {
            const char* pszTextBefore;
            unsigned int nVal;
            unsigned short usPortNetwork;
            ++(*ppszText);
            pszTextBefore = *ppszText;
            pszTextBefore = *ppszText;
            nVal =_parseDecimal ( ppszText );
            if ( nVal > 65535 || pszTextBefore == *ppszText )
                return 0;
            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
            *pnPort = usPortNetwork;
            return 1;
        }
        else
        {
            if ( NULL != pnPort )
                *pnPort = 0;
            return 1;
        }
    }

}

int ParseIPv4OrIPv6_2 ( const char* pszText,
        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
    const char* pszTextLocal = pszText;
    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}

use std::{
    net::{IpAddr, SocketAddr},
    str::FromStr,
};

#[derive(Clone, Debug)]
struct Addr {
    addr: IpAddr,
    port: Option<u16>,
}

impl std::fmt::Display for Addr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ipv = if self.addr.is_ipv4() { "4" } else { "6" };

        let hex = match self.addr {
            IpAddr::V4(addr) => u32::from(addr) as u128,
            IpAddr::V6(addr) => u128::from(addr),
        };

        match self.port {
            Some(p) => write!(
                f,
                "address: {}, port: {}, hex: {:x} (IPv{})",
                self.addr, p, hex, ipv
            ),

            None => write!(
                f,
                "address: {}, port: N/A, hex: {:x} (IPv{}) ",
                self.addr, hex, ipv
            ),
        }
    }
}

impl FromStr for Addr {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(addr) = s.parse::<IpAddr>() {
            Ok(Self { addr, port: None })
        } else if let Ok(sock) = s.parse::<SocketAddr>() {
            Ok(Self {
                addr: sock.ip(),
                port: Some(sock.port()),
            })
        } else {
            Err(())
        }
    }
}

fn print_addr(s: &str) {
    match s.parse::<Addr>() {
        Ok(addr) => println!("{}: {}", s, addr),
        _ => println!("{} not a valid address", s),
    }
}

fn main() {
    [
        "127.0.0.1",
        "127.0.0.1:80",
        "::1",
        "[::1]:80",
        "2605:2700:0:3::4713:93e3",
        "[2605:2700:0:3::4713:93e3]:80",
    ]
    .iter()
    .cloned()
    .for_each(print_addr);
}


Parse command-line arguments

#include <stdio.h>
int main(int argc, char **argv){
    int i;
    const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
    enum {CREATE,PRINT,TITLE,DATE,AUTH};
    if (argc<2) {
usage:   printf ("Usage: %s [commands]\n"
            "-c  Create new entry.\n"
            "-p  Print the latest entry.\n"
            "-t  Sort by title.\n"
            "-d  Sort by date.\n"
            "-a  Sort by author.\n",argv[0]);
        return 0;
    }
    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
    switch (i) {
    case CREATE:
...
    break;
    case PRINT:
...
    break;
...
...
    default:
    printf ("Unknown command..." ...);
    goto usage;
    }
    return 0;
}

use structopt::StructOpt;

#[derive(StructOpt)]
struct Opt {
    #[structopt(short)]
    b: bool,
    #[structopt(short, required = false, default_value = "")]
    s: String,
    #[structopt(short, required = false, default_value = "0")]
    n: i32,
}

fn main() {
    let opt = Opt::from_args();
    println!("b: {}", opt.b);
    println!("s: {}", opt.s);
    println!("n: {}", opt.n);
}


Parsing_Shunting-yard algorithm

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>

typedef struct {
	const char *s;
	int len, prec, assoc;
} str_tok_t;

typedef struct {
	const char * str;
	int assoc, prec;
	regex_t re;
} pat_t;

enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};

pat_t pat_ops[] = {
	{"^\\)",	A_NONE, -1},
	{"^\\*\\*",	A_R, 3},
	{"^\\^",	A_R, 3},
	{"^\\*",	A_L, 2},
	{"^/",		A_L, 2},
	{"^\\+",	A_L, 1},
	{"^-",		A_L, 1},
	{0}
};

pat_t pat_arg[] = {
	{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
	{"^[a-zA-Z_][a-zA-Z_0-9]*"},
	{"^\\(", A_L, -1},
	{0}
};

str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop()   stack[--l_stack]

void display(const char *s)
{
	int i;
	printf("\033[1;1H\033[JText | %s", s);
	printf("\nStack| ");
	for (i = 0; i < l_stack; i++)
		printf("%.*s ", stack[i].len, stack[i].s);
	printf("\nQueue| ");
	for (i = 0; i < l_queue; i++)
		printf("%.*s ", queue[i].len, queue[i].s);
	puts("\n\n<press enter>");
	getchar();
}

int prec_booster;

#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}

int init(void)
{
	int i;
	pat_t *p;

	for (i = 0, p = pat_ops; p[i].str; i++)
		if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
			fail("comp", p[i].str);

	for (i = 0, p = pat_arg; p[i].str; i++)
		if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
			fail("comp", p[i].str);

	return 1;
}

pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
	int i;
	regmatch_t m;

	while (*s == ' ') s++;
	*e = s;

	if (!*s) return &pat_eos;

	for (i = 0; p[i].str; i++) {
		if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
			continue;
		t->s = s;
		*e = s + (t->len = m.rm_eo - m.rm_so);
		return p + i;
	}
	return 0;
}

int parse(const char *s) {
	pat_t *p;
	str_tok_t *t, tok;

	prec_booster = l_queue = l_stack = 0;
	display(s);
	while (*s) {
		p = match(s, pat_arg, &tok, &s);
		if (!p || p == &pat_eos) fail("parse arg", s);

		if (p->prec == -1) {
			prec_booster += 100;
			continue;
		}
		qpush(tok);
		display(s);

re_op:		p = match(s, pat_ops, &tok, &s);
		if (!p) fail("parse op", s);

		tok.assoc = p->assoc;
		tok.prec = p->prec;

		if (p->prec > 0)
			tok.prec = p->prec + prec_booster;
		else if (p->prec == -1) {
			if (prec_booster < 100)
				fail("unmatched )", s);
			tok.prec = prec_booster;
		}

		while (l_stack) {
			t = stack + l_stack - 1;
			if (!(t->prec == tok.prec && t->assoc == A_L)
					&& t->prec <= tok.prec)
				break;
			qpush(spop());
			display(s);
		}

		if (p->prec == -1) {
			prec_booster -= 100;
			goto re_op;
		}

		if (!p->prec) {
			display(s);
			if (prec_booster)
				fail("unmatched (", s);
			return 1;
		}

		spush(tok);
		display(s);
	}

	if (p->prec > 0)
		fail("unexpected eol", s);

	return 1;
}

int main()
{
	int i;
	const char *tests[] = {
		"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
		"123",
		"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
		"(((((((1+2+3**(4 + 5))))))",
		"a^(b + c/d * .1e5)!",
		"(1**2)**3",
		"2 + 2 *",
		0
	};

	if (!init()) return 1;
	for (i = 0; tests[i]; i++) {
		printf("Testing string `%s'   <enter>\n", tests[i]);
		getchar();

		printf("string `%s': %s\n\n", tests[i],
			parse(tests[i]) ? "Ok" : "Error");
	}

	return 0;
}

type Number = f64;

#[derive(Debug, Copy, Clone, PartialEq)]
struct Operator {
    token: char,
    operation: fn(Number, Number) -> Number,
    precedence: u8,
    is_left_associative: bool,
}

#[derive(Debug, Clone, PartialEq)]
enum Token {
    Digit(Number),
    Operator(Operator),
    LeftParen,
    RightParen,
}

impl Operator {
    fn new_token(
        token: char,
        precedence: u8,
        is_left_associative: bool,
        operation: fn(Number, Number) -> Number,
    ) -> Token {
        Token::Operator(Operator {
            token: token,
            operation: operation,
            precedence: precedence,
            is_left_associative,
        })
    }

    fn apply(&self, x: Number, y: Number) -> Number {
        (self.operation)(x, y)
    }
}

trait Stack<T> {
    fn top(&self) -> Option<T>;
}

impl<T: Clone> Stack<T> for Vec<T> {
    fn top(&self) -> Option<T> {
        if self.is_empty() {
            return None;
        }
        self.last().cloned()
    }
}
fn lex_token(input: char) -> Result<Token, char> {
    let ret = match input {
        '0'...'9' => Token::Digit(input.to_digit(10).unwrap() as Number),
        '+' => Operator::new_token('+', 1, true, |x, y| x + y),
        '-' => Operator::new_token('-', 1, true, |x, y| x - y),
        '*' => Operator::new_token('*', 2, true, |x, y| x * y),
        '/' => Operator::new_token('/', 2, true, |x, y| x / y),
        '^' => Operator::new_token('^', 3, false, |x, y| x.powf(y)),
        '(' => Token::LeftParen,
        ')' => Token::RightParen,
        _ => return Err(input),
    };
    Ok(ret)
}

fn lex(input: String) -> Result<Vec<Token>, char> {
    input
        .chars()
        .filter(|c| !c.is_whitespace())
        .map(lex_token)
        .collect()
}

fn tilt_until(operators: &mut Vec<Token>, output: &mut Vec<Token>, stop: Token) -> bool {
    while let Some(token) = operators.pop() {
        if token == stop {
            return true;
        }
        output.push(token)
    }
    false
}

fn shunting_yard(tokens: Vec<Token>) -> Result<Vec<Token>, String> {
    let mut output: Vec<Token> = Vec::new();
    let mut operators: Vec<Token> = Vec::new();

    for token in tokens {
        match token {
            Token::Digit(_) => output.push(token),
            Token::LeftParen => operators.push(token),
            Token::Operator(operator) => {
                while let Some(top) = operators.top() {
                    match top {
                        Token::LeftParen => break,
                        Token::Operator(top_op) => {
                            let p = top_op.precedence;
                            let q = operator.precedence;
                            if (p > q) || (p == q && operator.is_left_associative) {
                                output.push(operators.pop().unwrap());
                            } else {
                                break;
                            }
                        }
                        _ => unreachable!("{:?} must not be on operator stack", token),
                    }
                }
                operators.push(token);
            }
            Token::RightParen => {
                if !tilt_until(&mut operators, &mut output, Token::LeftParen) {
                    return Err(String::from("Mismatched ')'"));
                }
            }
        }
    }

    if tilt_until(&mut operators, &mut output, Token::LeftParen) {
        return Err(String::from("Mismatched '('"));
    }

    assert!(operators.is_empty());
    Ok(output)
}

fn calculate(postfix_tokens: Vec<Token>) -> Result<Number, String> {
    let mut stack = Vec::new();

    for token in postfix_tokens {
        match token {
            Token::Digit(number) => stack.push(number),
            Token::Operator(operator) => {
                if let Some(y) = stack.pop() {
                    if let Some(x) = stack.pop() {
                        stack.push(operator.apply(x, y));
                        continue;
                    }
                }
                return Err(format!("Missing operand for operator '{}'", operator.token));
            }
            _ => unreachable!("Unexpected token {:?} during calculation", token),
        }
    }

    assert!(stack.len() == 1);
    Ok(stack.pop().unwrap())
}

fn run(input: String) -> Result<Number, String> {
    let tokens = match lex(input) {
        Ok(tokens) => tokens,
        Err(c) => return Err(format!("Invalid character: {}", c)),
    };
    let postfix_tokens = match shunting_yard(tokens) {
        Ok(tokens) => tokens,
        Err(message) => return Err(message),
    };

    calculate(postfix_tokens)
}