Chaos game

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

#define pi M_PI

int main(){

	time_t t;
	double side, vertices[3][3],seedX,seedY,windowSide;
	int i,iter,choice;

	printf("Enter triangle side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	windowSide = 10 + 2*side;

	initwindow(windowSide,windowSide,"Sierpinski Chaos");

	for(i=0;i<3;i++){
		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);
		putpixel(vertices[i][0],vertices[i][1],15);
	}

	srand((unsigned)time(&t));

	seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);
	seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);

	putpixel(seedX,seedY,15);

	for(i=0;i<iter;i++){
		choice = rand()%3;

		seedX = (seedX + vertices[choice][0])/2;
		seedY = (seedY + vertices[choice][1])/2;

		putpixel(seedX,seedY,15);
	}

	getch();

	closegraph();

	return 0;
}

extern crate image;
extern crate rand;

use rand::prelude::*;
use std::f32;

fn main() {
    let max_iterations = 50_000;
    let img_side = 800;
    let tri_size = 400.0;

    let mut imgbuf = image::ImageBuffer::new(img_side, img_side);

    let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3];
    for i in 0..vertices.len() {
        vertices[i][0] = (img_side as f32 / 2.0)
            + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).cos();
        vertices[i][1] = (img_side as f32 / 2.0)
            + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).sin();
    }
    for v in &vertices {
        imgbuf.put_pixel(v[0] as u32, v[1] as u32, image::Luma([255u8]));
    }
    println!("Verticies: {:?}", vertices);

    let mut rng = rand::thread_rng();
    let mut x = img_side as f32 / 2.0;
    let mut y = img_side as f32 / 2.0;
    for _ in 0..max_iterations {
        let choice = rng.gen_range(0..vertices.len());
        x = (x + vertices[choice][0]) / 2.0;
        y = (y + vertices[choice][1]) / 2.0;

        imgbuf.put_pixel(x as u32, y as u32, image::Luma([255u8]));
    }

    imgbuf.save("fractal.png").unwrap();
}


Circles of given radius through two points

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

typedef struct{
	double x,y;
	}point;

double distance(point p1,point p2)
{
	return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}

void findCircles(point p1,point p2,double radius)
{
	double separation = distance(p1,p2),mirrorDistance;

	if(separation == 0.0)
	{
		radius == 0.0 ? printf("\nNo circles can be drawn through (%.4f,%.4f)",p1.x,p1.y):
							 printf("\nInfinitely many circles can be drawn through (%.4f,%.4f)",p1.x,p1.y);
	}

	else if(separation == 2*radius)
	{
		printf("\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius);
	}

	else if(separation > 2*radius)
	{
		printf("\nGiven points are farther away from each other than a diameter of a circle with radius %.4f",radius);
	}

	else
	{
		mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2));

		printf("\nTwo circles are possible.");
		printf("\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius);
	}
}

int main()
{
    int i;

    point cases[] =
    {	{0.1234, 0.9876},    {0.8765, 0.2345},
	{0.0000, 2.0000},    {0.0000, 0.0000},
	{0.1234, 0.9876},    {0.1234, 0.9876},
	{0.1234, 0.9876},    {0.8765, 0.2345},
	{0.1234, 0.9876},    {0.1234, 0.9876}
    };

    double radii[] = {2.0,1.0,2.0,0.5,0.0};

    for(i=0;i<5;i++)
    {
	printf("\nCase %d)",i+1);
	findCircles(cases[2*i],cases[2*i+1],radii[i]);
    }

    return 0;
}

use std::fmt;

#[derive(Clone,Copy)]
struct Point {
    x: f64,
    y: f64
}

fn distance (p1: Point, p2: Point) -> f64 {
    ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({:.4}, {:.4})", self.x, self.y)
    }
}

fn describe_circle(p1: Point, p2: Point, r: f64) {
    let sep = distance(p1, p2);

    if sep == 0. {
        if r == 0. {
            println!("No circles can be drawn through {}", p1);
        } else {
            println!("Infinitely many circles can be drawn through {}", p1);
        }
    } else if sep == 2.0 * r {
        println!("Given points are opposite ends of a diameter of the circle with center ({:.4},{:.4}) and r {:.4}",
                (p1.x+p2.x) / 2.0, (p1.y+p2.y) / 2.0, r);
    } else if sep > 2.0 * r {
        println!("Given points are farther away from each other than a diameter of a circle with r {:.4}", r);
    } else {
        let mirror_dist = (r.powi(2) - (sep / 2.0).powi(2)).sqrt();

        println!("Two circles are possible.");
        println!("Circle C1 with center ({:.4}, {:.4}), r {:.4} and Circle C2 with center ({:.4}, {:.4}), r {:.4}",
                ((p1.x + p2.x) / 2.0) + mirror_dist * (p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 + mirror_dist*(p2.x-p1.x)/sep,
                r,
                (p1.x+p2.x) / 2.0 - mirror_dist*(p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 - mirror_dist*(p2.x-p1.x)/sep, r);
    }
}

fn main() {
    let points: Vec<(Point, Point)> = vec![
        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),
        (Point { x: 0.0000, y: 2.0000 }, Point { x: 0.0000, y: 0.0000 }),
        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }),
        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),
        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 })
    ];
    let radii: Vec<f64> = vec![2.0, 1.0, 2.0, 0.5, 0.0];

    for (p, r) in points.into_iter().zip(radii.into_iter()) {
        println!("\nPoints: ({}, {}), Radius: {:.4}", p.0, p.1, r);
        describe_circle(p.0, p.1, r);
    }
}


Circular primes

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

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 cycle(uint32_t n) {
    uint32_t m = n, p = 1;
    while (m >= 10) {
        p *= 10;
        m /= 10;
    }
    return m + 10 * (n % p);
}

bool is_circular_prime(uint32_t p) {
    if (!is_prime(p))
        return false;
    uint32_t p2 = cycle(p);
    while (p2 != p) {
        if (p2 < p || !is_prime(p2))
            return false;
        p2 = cycle(p2);
    }
    return true;
}

void test_repunit(uint32_t digits) {
    char* str = malloc(digits + 1);
    if (str == 0) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }
    memset(str, '1', digits);
    str[digits] = 0;
    mpz_t bignum;
    mpz_init_set_str(bignum, str, 10);
    free(str);
    if (mpz_probab_prime_p(bignum, 10))
        printf("R(%u) is probably prime.\n", digits);
    else
        printf("R(%u) is not prime.\n", digits);
    mpz_clear(bignum);
}

int main() {
    uint32_t p = 2;
    printf("First 19 circular primes:\n");
    for (int count = 0; count < 19; ++p) {
        if (is_circular_prime(p)) {
            if (count > 0)
                printf(", ");
            printf("%u", p);
            ++count;
        }
    }
    printf("\n");
    printf("Next 4 circular primes:\n");
    uint32_t repunit = 1, digits = 1;
    for (; repunit < p; ++digits)
        repunit = 10 * repunit + 1;
    mpz_t bignum;
    mpz_init_set_ui(bignum, repunit);
    for (int count = 0; count < 4; ) {
        if (mpz_probab_prime_p(bignum, 15)) {
            if (count > 0)
                printf(", ");
            printf("R(%u)", digits);
            ++count;
        }
        ++digits;
        mpz_mul_ui(bignum, bignum, 10);
        mpz_add_ui(bignum, bignum, 1);
    }
    mpz_clear(bignum);
    printf("\n");
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
    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 cycle(n: u32) -> u32 {
    let mut m: u32 = n;
    let mut p: u32 = 1;
    while m >= 10 {
        p *= 10;
        m /= 10;
    }
    m + 10 * (n % p)
}

fn is_circular_prime(p: u32) -> bool {
    if !is_prime(p) {
        return false;
    }
    let mut p2: u32 = cycle(p);
    while p2 != p {
        if p2 < p || !is_prime(p2) {
            return false;
        }
        p2 = cycle(p2);
    }
    true
}

fn test_repunit(digits: usize) {
    use rug::{integer::IsPrime, Integer};
    let repunit = "1".repeat(digits);
    let bignum = Integer::from_str_radix(&repunit, 10).unwrap();
    if bignum.is_probably_prime(10) != IsPrime::No {
        println!("R({}) is probably prime.", digits);
    } else {
        println!("R({}) is not prime.", digits);
    }
}

fn main() {
    use rug::{integer::IsPrime, Integer};
    println!("First 19 circular primes:");
    let mut count = 0;
    let mut p: u32 = 2;
    while count < 19 {
        if is_circular_prime(p) {
            if count > 0 {
                print!(", ");
            }
            print!("{}", p);
            count += 1;
        }
        p += 1;
    }
    println!();
    println!("Next 4 circular primes:");
    let mut repunit: u32 = 1;
    let mut digits: usize = 1;
    while repunit < p {
        repunit = 10 * repunit + 1;
        digits += 1;
    }
    let mut bignum = Integer::from(repunit);
    count = 0;
    while count < 4 {
        if bignum.is_probably_prime(15) != IsPrime::No {
            if count > 0 {
                print!(", ");
            }
            print!("R({})", digits);
            count += 1;
        }
        digits += 1;
        bignum = bignum * 10 + 1;
    }
    println!();
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
}


Colour bars_Display

#include<conio.h>

#define COLOURS 8

int main()
{
	int colour=0,i,j,MAXROW,MAXCOL;
	struct text_info tInfo;
	gettextinfo(&tInfo);
	MAXROW = tInfo.screenheight;
	MAXCOL = tInfo.screenwidth;
	textbackground(BLACK);
	clrscr();

	for(colour=0;colour<COLOURS;colour++)
	{
		getch();
		gotoxy(1+colour*MAXCOL/COLOURS,1);
		textbackground(colour);
		for(j=0;j<MAXROW;j++){
			for(i=0;i<MAXCOL/COLOURS;i++){
				cprintf(" ");
			}
		gotoxy(1+colour*MAXCOL/COLOURS,1+j);
		}
	}

	getch();
	textbackground(BLACK);

	return 0;
}

use pixels::{Pixels, SurfaceTexture};
use winit::event::*;
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Fullscreen, WindowBuilder};

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new()
        .with_title("Colour Bars")
        .with_decorations(false)
        .with_fullscreen(Some(Fullscreen::Borderless(None)))
        .build(&event_loop).unwrap();
    let size = window.inner_size();
    let texture = SurfaceTexture::new(size.width, size.height, &window);
    let mut image_buffer = Pixels::new(8, 1, texture).unwrap();
    let frame = image_buffer.get_frame();
    frame.copy_from_slice(&[
        0x00, 0x00, 0x00, 0xFF,
        0xFF, 0x00, 0x00, 0xFF,
        0x00, 0xFF, 0x00, 0xFF,
        0x00, 0x00, 0xFF, 0xFF,
        0xFF, 0x00, 0xFF, 0xFF,
        0x00, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0x00, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF,
    ]);

    image_buffer.render().unwrap();

    event_loop.run(move |ev, _, flow| {
        match ev {
            Event::WindowEvent {
                event: WindowEvent::KeyboardInput { input, .. }, ..
            } => {
                if input.virtual_keycode == Some(VirtualKeyCode::Escape) {
                    *flow = ControlFlow::Exit;
                }
            }
            Event::RedrawRequested(_) | Event::WindowEvent {
                event: WindowEvent::Focused(true), ..
            } => {
                image_buffer.render().unwrap();
            }
            _ => {}
        }
    });
}


Comments

*/

fn example() {

}

#[doc = "Unsugared outer Rustdoc comments.
        (outer attributes are not terminated by a semi-colon)"]
fn example() {
    #[doc = "Unsugared inner Rustdoc comments.
            (inner attributes are terminated by a semi-colon)
            See also https:
}


Consecutive primes with ascending or descending differences

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.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;
}

void longestSeq(int *primes, int pc, bool asc) {
    int i, j, d, pd = 0, lls = 1, lcs = 1;
    int longSeqs[25][10] = {{2}};
    int lsl[25] = {1};
    int currSeq[10] = {2};
    const char *dir = asc ? "ascending" : "descending";
    for (i = 1; i < pc; ++i) {
        d = primes[i] - primes[i-1];
        if ((asc && d <= pd) || (!asc && d >= pd)) {
            if (lcs > lsl[0]) {
                memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));
                lsl[0] = lcs;
                lls = 1;
            } else if (lcs == lsl[0]) {
                memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));
                lsl[lls++] = lcs;
            }
            currSeq[0] = primes[i-1];
            currSeq[1] = primes[i];
            lcs = 2;
        } else {
            currSeq[lcs++] = primes[i];
        }
        pd = d;
    }
    if (lcs > lsl[0]) {
        memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));
        lsl[0] = lcs;
        lls = 1;
    } else if (lcs == lsl[0]) {
        memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));
        lsl[lls++] = lcs;
    }
    printf("Longest run(s) of primes with %s differences is %d:\n", dir, lsl[0]);
    for (i = 0; i < lls; ++i) {
        int *ls = longSeqs[i];
        for (j = 0; j < lsl[i]-1; ++j) printf("%d (%d) ", ls[j], ls[j+1] - ls[j]);
        printf("%d\n", ls[lsl[i]-1]);
    }
    printf("\n");
}

int main() {
    const int limit = 999999;
    int i, j, pc = 0;
    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;
    }
    free(c);
    printf("For primes < 1 million:\n");
    longestSeq(primes, pc, true);
    longestSeq(primes, pc, false);
    free(primes);
    return 0;
}

fn print_diffs(vec: &[usize]) {
    for i in 0..vec.len() {
        if i > 0 {
            print!(" ({}) ", vec[i] - vec[i - 1]);
        }
        print!("{}", vec[i]);
    }
    println!();
}

fn main() {
    let limit = 1000000;
    let mut asc = Vec::new();
    let mut desc = Vec::new();
    let mut max_asc = Vec::new();
    let mut max_desc = Vec::new();
    let mut max_asc_len = 0;
    let mut max_desc_len = 0;
    for p in primal::Sieve::new(limit)
        .primes_from(2)
        .take_while(|x| *x < limit)
    {
        let alen = asc.len();
        if alen > 1 && p - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2] {
            asc = asc.split_off(alen - 1);
        }
        asc.push(p);
        if asc.len() >= max_asc_len {
            if asc.len() > max_asc_len {
                max_asc_len = asc.len();
                max_asc.clear();
            }
            max_asc.push(asc.clone());
        }
        let dlen = desc.len();
        if dlen > 1 && p - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2] {
            desc = desc.split_off(dlen - 1);
        }
        desc.push(p);
        if desc.len() >= max_desc_len {
            if desc.len() > max_desc_len {
                max_desc_len = desc.len();
                max_desc.clear();
            }
            max_desc.push(desc.clone());
        }
    }
    println!("Longest run(s) of ascending prime gaps up to {}:", limit);
    for v in max_asc {
        print_diffs(&v);
    }
    println!("\nLongest run(s) of descending prime gaps up to {}:", limit);
    for v in max_desc {
        print_diffs(&v);
    }
}


Copy a string

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

int
main()
{
	size_t len;
	char src[] = "Hello";
	char dst1[80], dst2[80];
	char *dst3, *ref;

	strcpy(dst1, src);

	len = strlen(src);
	if (len >= sizeof dst2) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}
	memcpy(dst2, src, len + 1);

	dst3 = strdup(src);
	if (dst3 == NULL) {

		perror("strdup");
		exit(1);
	}

	ref = src;

	memset(src, '-', 5);

	printf(" src: %s\n", src);
	printf("dst1: %s\n", dst1);
	printf("dst2: %s\n", dst2);
	printf("dst3: %s\n", dst3);
	printf(" ref: %s\n", ref);

	free(dst3);

	return 0;
}

fn main() {
    let s1 = "A String";
    let mut s2 = s1;

    s2 = "Another String";

    println!("s1 = {}, s2 = {}", s1, s2);
}


Count occurrences of a substring

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

int match(const char *s, const char *p, int overlap)
{
        int c = 0, l = strlen(p);

        while (*s != '\0') {
                if (strncmp(s++, p, l)) continue;
                if (!overlap) s += l - 1;
                c++;
        }
        return c;
}

int main()
{
        printf("%d\n", match("the three truths", "th", 0));
        printf("overlap:%d\n", match("abababababa", "aba", 1));
        printf("not:    %d\n", match("abababababa", "aba", 0));
        return 0;
}

fn main() {
    println!("{}","the three truths".matches("th").count());
    println!("{}","ababababab".matches("abab").count());
}


Create a file on magnetic tape

#include<stdio.h>

int main()
{
	FILE* fp = fopen("TAPE.FILE","w");

	fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
	fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
	fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
	fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
	fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
	fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
	fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
	fprintf(fp,"EOF");

	fclose(fp);

	return 0;
}

use std::io::Write;
use std::fs::File;

fn main() -> std::io::Result<()> {
    File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
}


Cuban primes

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

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

struct PrimeArray allocate() {
    struct PrimeArray primes;

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

    return primes;
}

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

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

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

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

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

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

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

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

    deallocate(&primes);
    return 0;
}

use std::time::Instant;
use separator::Separatable;

const NUMBER_OF_CUBAN_PRIMES: usize = 200;
const COLUMNS: usize = 10;
const LAST_CUBAN_PRIME: usize = 100_000;

fn main() {
    println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME);
    let start = Instant::now();

    let mut i: u64 = 0;
    let mut j: u64 = 1;
    let mut index: usize = 0;
    let mut cuban_primes = Vec::new();
    let mut cuban: u64 = 0;
    while index < 100_000 {
        cuban = {j += 1; j}.pow(3) - {i += 1; i}.pow(3);
        if primal::is_prime(cuban) {
            if index < NUMBER_OF_CUBAN_PRIMES {
                cuban_primes.push(cuban);
            }
            index += 1;
        }
    }

    let elapsed = start.elapsed();
    println!("THE {} FIRST CUBAN PRIMES:", NUMBER_OF_CUBAN_PRIMES);
    cuban_primes
        .chunks(COLUMNS)
        .map(|chunk| {
            chunk.iter()
                .map(|item| {
                    print!("{}\t", item)
                })
                .for_each(drop);
            println!("");
        })
        .for_each(drop);
    println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string());
    println!("Elapsed time: {:?}", elapsed);
}


Curzon numbers

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

uint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) {
    if (mod == 1) return 0;
    uint64_t result = 1;
    base %= mod;
    for (; exp > 0; exp >>= 1) {
        if ((exp & 1) == 1) result = (result * base) % mod;
        base = (base * base) % mod;
    }
    return result;
}

bool isCurzon(uint64_t n, uint64_t k) {
    const uint64_t r = k * n;
    return modPow(k, n, r+1) == r;
}

int main() {
    uint64_t k, n, count;
    setlocale(LC_NUMERIC, "");
    for (k = 2; k <= 10; k += 2) {
        printf("Curzon numbers with base %ld:\n", k);
        for (n = 1, count = 0; count < 50; ++n) {
            if (isCurzon(n, k)) {
                printf("%4ld ", n);
                if (++count % 10 == 0) printf("\n");
            }
        }
        for (;;) {
            if (isCurzon(n, k)) ++count;
            if (count == 1000) break;
            ++n;
        }
        printf("1,000th Curzon number with base %ld: %'ld\n\n", k, n);
    }
    return 0;
}

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_curzon(n: usize, k: usize) -> bool {
    let m = k * n + 1;
    modpow(k, n, m) + 1 == m

}

fn main() {
    for k in (2..=10).step_by(2) {
        println!("Curzon numbers with base {k}:");
        let mut count = 0;
        let mut n = 1;
        while count < 50 {
            if is_curzon(n, k) {
                count += 1;
                print!("{:4}{}", n, if count % 10 == 0 { "\n" } else { " " });
            }
            n += 1;
        }
        loop {
            if is_curzon(n, k) {
                count += 1;
                if count == 1000 {
                    break;
                }
            }
            n += 1;
        }
        println!("1000th Curzon number with base {k}: {n}\n");
    }
}


Cut a rectangle

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

typedef unsigned char byte;
byte *grid = 0;

int w, h, len;
unsigned long long cnt;

static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
	int i, t;

	if (!y || y == h || !x || x == w) {
		cnt += 2;
		return;
	}

	t = y * (w + 1) + x;
	grid[t]++, grid[len - t]++;

	for (i = 0; i < 4; i++)
		if (!grid[t + next[i]])
			walk(y + dir[i][0], x + dir[i][1]);

	grid[t]--, grid[len - t]--;
}

unsigned long long solve(int hh, int ww, int recur)
{
	int t, cx, cy, x;

	h = hh, w = ww;

	if (h & 1) t = w, w = h, h = t;
	if (h & 1) return 0;
	if (w == 1) return 1;
	if (w == 2) return h;
	if (h == 2) return w;

	cy = h / 2, cx = w / 2;

	len = (h + 1) * (w + 1);
	grid = realloc(grid, len);
	memset(grid, 0, len--);

	next[0] = -1;
	next[1] = -w - 1;
	next[2] = 1;
	next[3] = w + 1;

	if (recur) cnt = 0;
	for (x = cx + 1; x < w; x++) {
		t = cy * (w + 1) + x;
		grid[t] = 1;
		grid[len - t] = 1;
		walk(cy - 1, x);
	}
	cnt++;

	if (h == w)
		cnt *= 2;
	else if (!(w & 1) && recur)
		solve(w, h, 0);

	return cnt;
}

int main()
{
	int y, x;
	for (y = 1; y <= 10; y++)
		for (x = 1; x <= y; x++)
			if (!(x & 1) || !(y & 1))
				printf("%d x %d: %llu\n", y, x, solve(y, x, 1));

	return 0;
}

fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) {
    if x == 0 || y == 0 || x == w || y == h {
        *count += 1;
        return;
    }

    vis[y][x] = true;
    vis[h - y][w - x] = true;

    if x != 0 && ! vis[y][x - 1] {
        cwalk(&mut vis, count, w, h, y, x - 1, d | 1);
    }
    if d & 1 != 0 && x < w && ! vis[y][x+1] {
        cwalk(&mut vis, count, w, h, y, x + 1, d | 1);
    }
    if y != 0 && ! vis[y - 1][x] {
        cwalk(&mut vis, count, w, h, y - 1, x, d | 2);
    }
    if d & 2 != 0 && y < h && ! vis[y + 1][x] {
        cwalk(&mut vis, count, w, h, y + 1, x, d | 2);
    }

    vis[y][x] = false;
    vis[h - y][w - x] = false;
}

fn count_only(x: usize, y: usize) -> isize {
    let mut count = 0;
    let mut w = x;
    let mut h = y;

    if (h * w) & 1 != 0 {
        return count;
    }
    if h & 1 != 0 {
        std::mem::swap(&mut w, &mut h);
    }

    let mut vis = vec![vec![false; w + 1]; h + 1];
    vis[h / 2][w / 2] = true;

    if w & 1 != 0 {
        vis[h / 2][w / 2 + 1] = true;
    }
    let mut res;
    if w > 1 {
        cwalk(&mut vis, &mut count, w, h, h / 2, w / 2 - 1, 1);
        res = 2 * count - 1;
        count = 0;
        if w != h {
            cwalk(&mut vis, &mut count, w, h, h / 2 + 1, w / 2, if w & 1 != 0 { 3 } else { 2 });
        }
        res += 2 * count - if w & 1 == 0 { 1 } else { 0 };
    }
    else {
        res = 1;
    }

    if w == h {
        res = 2 * res + 2;
    }
    res
}

fn main() {
    for y in 1..10 {
        for x in 1..y + 1 {
            if x & 1 == 0 || y & 1 == 0 {
                println!("{} x {}: {}", y, x, count_only(x, y));
            }
        }
    }
}


Deceptive numbers

#include <stdio.h>

unsigned modpow(unsigned b, unsigned e, unsigned m)
{
    unsigned p;
    for (p = 1; e; e >>= 1) {
        if (e & 1)
            p = p * b % m;
        b = b * b % m;
    }
    return p;
}

int is_deceptive(unsigned n)
{
    unsigned x;
    if (n & 1 && n % 3 && n % 5) {
        for (x = 7; x * x <= n; x += 6) {
            if (!(n % x && n % (x + 4)))
                return modpow(10, n - 1, n) == 1;
        }
    }
    return 0;
}

int main(void)
{
    unsigned c, i = 49;
    for (c = 0; c != 50; ++i) {
        if (is_deceptive(i)) {
            printf(" %u", i);
            ++c;
        }
    }
    return 0;
}

fn main() {
    println!("First 100 deceptive numbers:");
    use rug::Integer;
    let mut repunit = Integer::from(11);
    let mut n: u32 = 3;
    let mut count = 0;
    while count != 100 {
        if n % 3 != 0 && n % 5 != 0 && !primal::is_prime(n as u64) && repunit.is_divisible_u(n) {
            print!("{:6}", n);
            count += 1;
            if count % 10 == 0 {
                println!();
            } else {
                print!(" ");
            }
        }
        n += 2;
        repunit *= 100;
        repunit += 11;
    }
}


Deepcopy

#include<stdio.h>

typedef struct{
	int a;
}layer1;

typedef struct{
	layer1 l1;
	float b,c;
}layer2;

typedef struct{
	layer2 l2;
	layer1 l1;
	int d,e;
}layer3;

void showCake(layer3 cake){
	printf("\ncake.d = %d",cake.d);
	printf("\ncake.e = %d",cake.e);
	printf("\ncake.l1.a = %d",cake.l1.a);
	printf("\ncake.l2.b = %f",cake.l2.b);
	printf("\ncake.l2.l1.a = %d",cake.l2.l1.a);
}

int main()
{
	layer3 cake1,cake2;

	cake1.d = 1;
	cake1.e = 2;
	cake1.l1.a = 3;
	cake1.l2.b = 4;
	cake1.l2.l1.a = 5;

	printf("Cake 1 is : ");
	showCake(cake1);

	cake2 = cake1;

	cake2.l2.b += cake2.l2.l1.a;

	printf("\nCake 2 is : ");
	showCake(cake2);

	return 0;
}

#[derive(Clone)]
struct Tree<T> {
    left: Leaf<T>,
    data: T,
    right: Leaf<T>,
}

type Leaf<T> = Option<Box<Tree<T>>>;

impl<T> Tree<T> {
    fn root(data: T) -> Self {
        Self { left: None, data, right: None }
    }

    fn leaf(d: T) -> Leaf<T> {
        Some(Box::new(Self::root(d)))
    }
}

fn main() {
    let mut tree = Tree::root([4, 5, 6]);
    tree.right = Tree::leaf([1, 2, 3]);
    tree.left = Tree::leaf([7, 8, 9]);

    let newtree = tree.clone();
}


Determinant and permanent

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

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

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

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

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

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

	return det_in(m, n, perm);
}

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

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

	return 0;
}


Dice game probabilities

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

typedef uint32_t uint;
typedef uint64_t ulong;

ulong ipow(const uint x, const uint y) {
    ulong result = 1;
    for (uint i = 1; i <= y; i++)
        result *= x;
    return result;
}

uint min(const uint x, const uint y) {
    return (x < y) ? x : y;
}

void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {
    if (n_dice == 0) {
        counts[s]++;
        return;
    }

    for (uint i = 1; i < n_sides + 1; i++)
        throw_die(n_sides, n_dice - 1, s + i, counts);
}

double beating_probability(const uint n_sides1, const uint n_dice1,
                           const uint n_sides2, const uint n_dice2) {
    const uint len1 = (n_sides1 + 1) * n_dice1;
    uint C1[len1];
    for (uint i = 0; i < len1; i++)
        C1[i] = 0;
    throw_die(n_sides1, n_dice1, 0, C1);

    const uint len2 = (n_sides2 + 1) * n_dice2;
    uint C2[len2];
    for (uint j = 0; j < len2; j++)
        C2[j] = 0;
    throw_die(n_sides2, n_dice2, 0, C2);

    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));

    double tot = 0;
    for (uint i = 0; i < len1; i++)
        for (uint j = 0; j < min(i, len2); j++)
            tot += (double)C1[i] * C2[j] / p12;
    return tot;
}

int main() {
    printf("%1.16f\n", beating_probability(4, 9, 6, 6));
    printf("%1.16f\n", beating_probability(10, 5, 7, 6));
    return 0;
}

fn get_totals(dice: usize, faces: usize) -> Vec<f64> {
    let mut result = vec![1.0; faces + 1];
    for d in 2..=dice {
        let mut tmp = vec![0.0; d * faces + 1];
        for i in d - 1..result.len() {
            for j in 1..=faces {
                tmp[i + j] += result[i];
            }
        }
        result = tmp;
    }
    result
}

fn probability(dice1: usize, faces1: usize, dice2: usize, faces2: usize) -> f64 {
    let totals1 = get_totals(dice1, faces1);
    let totals2 = get_totals(dice2, faces2);
    let mut wins = 0.0;
    let mut total = 0.0;
    for i in dice1..totals1.len() {
        for j in dice2..totals2.len() {
            let n = totals1[i] * totals2[j];
            total += n;
            if j < i {
                wins += n;
            }
        }
    }
    wins / total
}

fn main() {
    println!("{}", probability(9, 4, 6, 6));
    println!("{}", probability(5, 10, 6, 7));
}


Doomsday rule

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

typedef struct {
    uint16_t year;
    uint8_t month;
    uint8_t day;
} Date;

bool leap(uint16_t year) {
    return year%4==0 && (year%100!=0 || year%400==0);
}

const char *weekday(Date date) {
    static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
    static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
    static const char *days[] = {
        "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"
    };

    unsigned c = date.year/100, r = date.year%100;
    unsigned s = r/12, t = r%12;

    unsigned c_anchor = (5 * (c%4) + 2) % 7;
    unsigned doom = (s + t + (t/4) + c_anchor) % 7;
    unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
    return days[(doom+date.day-anchor+7)%7];
}

int main(void) {
    const char *past = "was", *future = "will be";
    const char *months[] = { "",
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    };

    const Date dates[] = {
        {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
        {2077,2,12}, {2101,4,2}
    };

    int i;
    for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
        printf("%s %d, %d %s on a %s.\n",
            months[dates[i].month], dates[i].day, dates[i].year,
            dates[i].year > 2021 ? future : past,
            weekday(dates[i]));
    }

    return 0;
}

fn day_of_week(year: u32, month: u32, day: u32) -> u32 {
    const LEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5];
    const NONLEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5];
    assert!(year > 1581 && year < 10000);
    assert!(month >= 1 && month <= 12);
    assert!(day >= 1 && day <= 31);
    let doomsday = (2 + 5 * (year % 4) + 4 * (year % 100) + 6 * (year % 400)) % 7;
    let anchorday = if year % 4 != 0 || (year % 100 == 0 && year % 400 != 0) {
        NONLEAPYEAR_FIRSTDOOMSDAYS[month as usize - 1]
    } else {
        LEAPYEAR_FIRSTDOOMSDAYS[month as usize - 1]
    };
    (doomsday + day + 7 - anchorday) % 7
}

fn print_day_of_week(year: u32, month: u32, day: u32) {
    const DAY_NAMES: [&str; 7] = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ];
    println!(
        "{:04}-{:02}-{:02}: {}",
        year,
        month,
        day,
        DAY_NAMES[day_of_week(year, month, day) as usize]
    );
}

fn main() {
    print_day_of_week(1800, 1, 6);
    print_day_of_week(1875, 3, 29);
    print_day_of_week(1915, 12, 7);
    print_day_of_week(1970, 12, 23);
    print_day_of_week(2043, 5, 14);
    print_day_of_week(2077, 2, 12);
    print_day_of_week(2101, 4, 2);
}


Elementary cellular automaton_Random number generator

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

typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))

void evolve(ull state, int rule)
{
	int i, p, q, b;

	for (p = 0; p < 10; p++) {
		for (b = 0, q = 8; q--; ) {
			ull st = state;
			b |= (st&1) << q;

			for (state = i = 0; i < N; i++)
				if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
					state |= B(i);
		}
		printf(" %d", b);
	}
	putchar('\n');
	return;
}

int main(void)
{
	evolve(1, 30);
	return 0;
}

fn main() {
    struct WolfGen(ElementaryCA);
    impl WolfGen {
        fn new() -> WolfGen {
            let (_, ca) = ElementaryCA::new(30);
            WolfGen(ca)
        }
        fn next(&mut self) -> u8 {
            let mut out = 0;
            for i in 0..8 {
                out |= ((1 & self.0.next())<<i)as u8;
            }
            out
        }
    }
    let mut gen = WolfGen::new();
    for _ in 0..10 {
        print!("{} ", gen.next());
    }
}


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

#define MAXLEN 961

int makehist(char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}

double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}

int main(void){
	char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	FILE *f;
	f=fopen("entropy.c","r");
	for(len=0;!feof(f);len++)S[len]=fgetc(f);
	S[--len]='\0';
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);

	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}

use std::fs::File;
use std::io::{Read, BufReader};

fn entropy<I: IntoIterator<Item = u8>>(iter: I) -> f32 {
    let mut histogram = [0u64; 256];
    let mut len = 0u64;

    for b in iter {
        histogram[b as usize] += 1;
        len += 1;
    }

    histogram
        .iter()
        .cloned()
        .filter(|&h| h > 0)
        .map(|h| h as f32 / len as f32)
        .map(|ratio| -ratio * ratio.log2())
        .sum()
}

fn main() {
    let name = std::env::args().nth(0).expect("Could not get program name.");
    let file = BufReader::new(File::open(name).expect("Could not read file."));
    println!("Entropy is {}.", entropy(file.bytes().flatten()));
}


Erdős-primes

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

#define LIMIT 1000000
#define LOWER_LIMIT 2500

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;
}

int main() {
    int i, j, fact, ec = 0, ec2 = 0, lastErdos = 0;
    bool found;
    bool *c = sieve(LIMIT-1);
    int erdos[30];
    for (i = 2; i < LIMIT;) {
        if (!c[i]) {
            j = 1;
            fact = 1;
            found = true;
            while (fact < i) {
                if (!c[i-fact]) {
                    found = false;
                    break;
                }
                ++j;
                fact *= j;
            }
            if (found) {
                if (i < LOWER_LIMIT) erdos[ec2++] = i;
                lastErdos = i;
                ++ec;
            }
        }
        i = (i > 2) ? i + 2 : i + 1;
    }
    setlocale(LC_NUMERIC, "");
    printf("The %'d Erdős primes under %'d are:\n", ec2, LOWER_LIMIT);
    for (i = 0; i < ec2; ++i) {
        printf("%6d ", erdos[i]);
        if (!((i+1)%10)) printf("\n");
    }
    printf("\n\nThe %'dth Erdős prime is %'d.\n", ec, lastErdos);
    free(c);
    return 0;
}

use std::collections::HashSet;

fn erdos_primes() -> impl std::iter::Iterator<Item = usize> {
    let mut primes = HashSet::new();
    let mut all_primes = primal::Primes::all();
    std::iter::from_fn(move || {
        'all_primes: for p in all_primes.by_ref() {
            primes.insert(p);
            let mut k = 1;
            let mut f = 1;
            while f < p {
                if primes.contains(&(p - f)) {
                    continue 'all_primes;
                }
                k += 1;
                f *= k;
            }
            return Some(p);
        }
        None
    })
}

fn main() {
    let mut count = 0;
    println!("Erd\u{151}s primes less than 2500:");
    for p in erdos_primes().take_while(|x| *x < 2500) {
        count += 1;
        if count % 10 == 0 {
            println!("{:4}", p);
        } else {
            print!("{:4} ", p);
        }
    }
    println!();
    if let Some(p) = erdos_primes().nth(7874) {
        println!("\nThe 7875th Erd\u{151}s prime is {}.", p);
    }
}


Esthetic numbers

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

typedef int bool;
typedef unsigned long long ull;

#define TRUE 1
#define FALSE 0

char as_digit(int d) {
    return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}

void revstr(char *str) {
    int i, len = strlen(str);
    char t;
    for (i = 0; i < len/2; ++i) {
        t = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = t;
    }
}

char* to_base(char s[], ull n, int b) {
    int i = 0;
    while (n) {
        s[i++] = as_digit(n % b);
        n /= b;
    }
    s[i] = '\0';
    revstr(s);
    return s;
}

ull uabs(ull a, ull  b) {
    return a > b ? a - b : b - a;
}

bool is_esthetic(ull n, int b) {
    int i, j;
    if (!n) return FALSE;
    i = n % b;
    n /= b;
    while (n) {
        j = n % b;
        if (uabs(i, j) != 1) return FALSE;
        n /= b;
        i = j;
    }
    return TRUE;
}

ull esths[45000];
int le = 0;

void dfs(ull n, ull m, ull i) {
    ull d, i1, i2;
    if (i >= n && i <= m) esths[le++] = i;
    if (i == 0 || i > m) return;
    d = i % 10;
    i1 = i * 10 + d - 1;
    i2 = i1 + 2;
    if (d == 0) {
        dfs(n, m, i2);
    } else if (d == 9) {
        dfs(n, m, i1);
    } else {
        dfs(n, m, i1);
        dfs(n, m, i2);
    }
}

void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
    int i;
    le = 0;
    for (i = 0; i < 10; ++i) {
        dfs(n2, m2, i);
    }
    printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
    if (all) {
        for (i = 0; i < le; ++i) {
            printf("%llu ", esths[i]);
            if (!(i+1)%per_line) printf("\n");
        }
    } else {
        for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
        printf("\n............\n");
        for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
    }
    printf("\n\n");
}

int main() {
    ull n;
    int b, c;
    char ch[15] = {0};
    for (b = 2; b <= 16; ++b) {
        printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
        for (n = 1, c = 0; c < 6 * b; ++n) {
            if (is_esthetic(n, b)) {
                if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
            }
        }
        printf("\n\n");
    }
    char *oldLocale = setlocale(LC_NUMERIC, NULL);
    setlocale(LC_NUMERIC, "");

    list_esths(1000, 1010, 9999, 9898, 16, TRUE);
    list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
    list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
    list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
    list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
    setlocale(LC_NUMERIC, oldLocale);
    return 0;
}

fn next_esthetic_number(base: u64, n: u64) -> u64 {
    if n + 1 < base {
        return n + 1;
    }
    let mut a = n / base;
    let mut b = a % base;
    if n % base + 1 == b && b + 1 < base {
        return n + 2;
    }
    a = next_esthetic_number(base, a);
    b = a % base;
    a * base + if b == 0 { 1 } else { b - 1 }
}

fn print_esthetic_numbers(min: u64, max: u64, numbers_per_line: usize) {
    let mut numbers = Vec::new();
    let mut n = next_esthetic_number(10, min - 1);
    while n <= max {
        numbers.push(n);
        n = next_esthetic_number(10, n);
    }
    let count = numbers.len();
    println!(
        "Esthetic numbers in base 10 between {} and {} ({}):",
        min, max, count
    );
    if count > 200 {
        for i in 0..numbers_per_line {
            if i != 0 {
                print!(" ");
            }
            print!("{}", numbers[i]);
        }
        println!("\n............\n");
        for i in 0..numbers_per_line {
            if i != 0 {
                print!(" ");
            }
            print!("{}", numbers[count - numbers_per_line + i]);
        }
        println!();
    } else {
        for i in 0..count {
            print!("{}", numbers[i]);
            if (i + 1) % numbers_per_line == 0 {
                println!();
            } else {
                print!(" ");
            }
        }
        if count % numbers_per_line != 0 {
            println!();
        }
    }
}

fn main() {
    for base in 2..=16 {
        let min = base * 4;
        let max = base * 6;
        println!(
            "Esthetic numbers in base {} from index {} through index {}:",
            base, min, max
        );
        let mut n = 0;
        for index in 1..=max {
            n = next_esthetic_number(base, n);
            if index >= min {
                print!("{} ", radix_fmt::radix(n, base as u8));
            }
        }
        println!("\n");
    }

    let mut min = 1000;
    let mut max = 9999;
    print_esthetic_numbers(min, max, 16);
    println!();

    min = 100000000;
    max = 130000000;
    print_esthetic_numbers(min, max, 8);
    println!();

    for i in 0..3 {
        min *= 1000;
        max *= 1000;
        let numbers_per_line = match i {
            0 => 7,
            1 => 5,
            _ => 4,
        };
        print_esthetic_numbers(min, max, numbers_per_line);
        println!();
    }
}


Euler's constant 0.5772...

fn gamma(N: u32) -> f64 {

    return 1f64 / 2f64 - 1f64 / 3f64
        + ((2..=N).map(|n| {
            let power: u32 = 2u32.pow(n);
            let mut sign: f64 = -1f64;
            let mut term: f64 = 0f64;

            for denominator in power..=(2 * power - 1) {
                sign *= -1f64;
                term += sign / f64::from(denominator);
            }

            return f64::from(n) * term;
        }))
        .sum::<f64>();
}

fn main() {
    println!("{}", gamma(23));
}


Exceptions

#include <setjmp.h>

enum { MY_EXCEPTION = 1 };

jmp_buf env;

void foo()
{
  longjmp(env, MY_EXCEPTION);
}

void call_foo()
{
  switch (setjmp(env)) {
  case 0:
    foo();
    break;
  case MY_EXCEPTION:

    break;
  default:

  }
}

use std::io::{Error, ErrorKind};

fn valid_function() -> Result<usize, Error> {
    Ok(100)
}

fn errored_function() -> Result<usize, Error> {
    Err(Error::new(ErrorKind::Other, "Something wrong happened."))
}

fn panicking_function() {
    panic!("Unrecoverable state reached");
}

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

    #[test]
    fn test_valid_function() {
        let result = match valid_function() {
            Ok(number) => number,
            Err(_) => panic!("This is not going to happen"),
        };
        assert_eq!(result, 100);
    }

    #[test]
    fn test_errored_function() {
        let result = match errored_function() {
            Ok(_) => panic!("This is not going to happen"),
            Err(e) => {
                assert_eq!(e.to_string(), "Something wrong happened.");
                0
            }
        };
        assert_eq!(result, 0);
    }

    #[test]
    #[should_panic]
    fn test_panicking_function() {
        panicking_function();
    }
}


Execute Brain____

#include <stdio.h>
int main(){
     int ptr=0, i=0, cell[7];
     for( i=0; i<7; ++i) cell[i]=0;
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 8;
     while(cell[ptr])
     {
          ptr-= 1;
          if(ptr<0) perror("Program pointer underflow");
          cell[ptr]+= 9;
          ptr+= 1;
          if(ptr>=7) perror("Program pointer overflow");
          cell[ptr]-= 1;
     }
     ptr-= 1;
     if(ptr<0) perror("Program pointer underflow");
     putchar(cell[ptr]);
     ptr+= 2;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 1;
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 1;
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 2;
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     while(cell[ptr])
     {
          cell[ptr]-= 1;
     }
     cell[ptr]+= 1;
     ptr-= 1;
     if(ptr<0) perror("Program pointer underflow");
     while(cell[ptr])
     {
          ptr+= 1;
          if(ptr>=7) perror("Program pointer overflow");
          while(cell[ptr])
          {
               cell[ptr]-= 1;
               ptr+= 1;
               if(ptr>=7) perror("Program pointer overflow");
               cell[ptr]+= 1;
               ptr-= 2;
               if(ptr<0) perror("Program pointer underflow");
               cell[ptr]+= 4;
               ptr+= 1;
               if(ptr>=7) perror("Program pointer overflow");
          }
          ptr-= 2;
          if(ptr<0) perror("Program pointer underflow");
     }
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     putchar(cell[ptr]);
     cell[ptr]+= 7;
     putchar(cell[ptr]);
     putchar(cell[ptr]);
     cell[ptr]+= 3;
     putchar(cell[ptr]);
     ptr+= 2;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 7;
     putchar(cell[ptr]);
     ptr-= 3;
     if(ptr<0) perror("Program pointer underflow");
     while(cell[ptr])
     {
          while(cell[ptr])
          {
               cell[ptr]-= 1;
          }
          ptr-= 1;
          if(ptr<0) perror("Program pointer underflow");
          while(cell[ptr])
          {
               cell[ptr]-= 1;
          }
          ptr+= 1;
          if(ptr>=7) perror("Program pointer overflow");
     }
     ptr-= 1;
     if(ptr<0) perror("Program pointer underflow");
     cell[ptr]+= 15;
     putchar(cell[ptr]);
     ptr+= 2;
     if(ptr>=7) perror("Program pointer overflow");
     putchar(cell[ptr]);
     cell[ptr]+= 3;
     putchar(cell[ptr]);
     cell[ptr]-= 6;
     putchar(cell[ptr]);
     cell[ptr]-= 8;
     putchar(cell[ptr]);
     ptr+= 2;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 1;
     putchar(cell[ptr]);
     ptr+= 1;
     if(ptr>=7) perror("Program pointer overflow");
     cell[ptr]+= 4;
     putchar(cell[ptr]);
     return 0;
}

use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println!("Usage: {} [path] (--debug)", args[0]);
        return;
    }

    let src: Vec<char> = {
        let mut buf = String::new();
        match File::open(&args[1])
        {
            Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); }
            Err(e)    => {
                println!("Error opening '{}': {}", args[1], e);
                return;
            }
        }

        buf.chars().collect()
    };

    let debug = args.contains(&"--debug".to_owned());

    let brackets: HashMap<usize, usize> = {
        let mut m = HashMap::new();
        let mut scope_stack = Vec::new();
        for (idx, ch) in src.iter().enumerate() {
            match ch {
                &'[' => { scope_stack.push(idx); }
                &']' => { m.insert(scope_stack.pop().unwrap(), idx); }
                _    => {  }
            }
        }

        m
    };

    let mut pc: usize = 0;
    let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000];
    let mut ptr: usize = 0;
    let mut stack: Vec<usize> = Vec::new();

    let stdin_ = stdin();
    let mut reader = stdin_.lock().bytes();
    while pc < src.len() {
        let Wrapping(val) = mem[ptr];

        if debug {
            println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}", pc, ptr, val, stack.len(), src[pc]);
        }

        const ONE: Wrapping<u8> = Wrapping(1);
        match src[pc] {
            '>' => { ptr += 1; }
            '<' => { ptr -= 1; }

            '+' => { mem[ptr] = mem[ptr] + ONE; }
            '-' => { mem[ptr] = mem[ptr] - ONE; }

            '[' => {
                if val == 0 {
                    pc = brackets[&pc];
                } else {
                    stack.push(pc);
                }
            }
            ']' => {
                let matching_bracket = stack.pop().unwrap();
                if val != 0 {
                    pc = matching_bracket - 1;
                }
            }

            '.' => {
                if debug {
                    println!("(BFDB) STDOUT: '{}'", val as char);
                } else {
                    print!("{}", val as char);
                }
            }
            ',' => {
                mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
            }

            _   => {  }
        }

        pc += 1;
    }
}


Execute HQ9+

void runCode(const char *code)
{
    int c_len = strlen(code);
    int i, bottles;
    unsigned accumulator=0;
    for(i=0;i<c_len;i++)
    {
        switch(code[i])
        {
            case 'Q':
                printf("%s\n", code);
                break;

            case 'H':
                printf("Hello, world!\n");
                break;

            case '9':

                bottles = 99;
                do {
                    printf("%d bottles of beer on the wall\n", bottles);
                    printf("%d bottles of beer\n", bottles);
                    printf("Take one down, pass it around\n");
                    printf("%d bottles of beer on the wall\n\n", --bottles);
                } while( bottles > 0 );
                break;

            case '+':

                accumulator++;
                break;
        }
    }
};

use std::env;

#[allow(unused_variables)]
fn execute(code: &str) {
    let mut accumulator = 0;

    for c in code.chars() {
        match c {
            'Q' => println!("{}", code),
            'H' => println!("Hello, World!"),
            '9' => {
                for n in (1..100).rev() {
                    println!("{} bottles of beer on the wall", n);
                    println!("{} bottles of beer", n);
                    println!("Take one down, pass it around");
                    if (n - 1) > 1 {
                        println!("{} bottles of beer on the wall\n", n - 1);
                    } else {
                        println!("1 bottle of beer on the wall\n");
                    }
                }
            }
            '+' => accumulator += 1,
            _ => panic!("Invalid character '{}' found in source.", c),
        }
    }
}

fn main() {
    execute(&env::args().nth(1).unwrap());
}


Extra primes

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

unsigned int next_prime_digit_number(unsigned int n) {
    if (n == 0)
        return 2;
    switch (n % 10) {
    case 2:
        return n + 1;
    case 3:
    case 5:
        return n + 2;
    default:
        return 2 + next_prime_digit_number(n/10) * 10;
    }
}

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if ((n & 1) == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    if (n % 5 == 0)
        return n == 5;
    static const unsigned int wheel[] = { 4,2,4,2,4,6,2,6 };
    unsigned int p = 7;
    for (;;) {
        for (int w = 0; w < sizeof(wheel)/sizeof(wheel[0]); ++w) {
            if (p * p > n)
                return true;
            if (n % p == 0)
                return false;
            p += wheel[w];
        }
    }
}

unsigned int digit_sum(unsigned int n) {
    unsigned int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int main() {
    setlocale(LC_ALL, "");
    const unsigned int limit1 = 10000;
    const unsigned int limit2 = 1000000000;
    const int last = 10;
    unsigned int p = 0, n = 0;
    unsigned int extra_primes[last];
    printf("Extra primes under %'u:\n", limit1);
    while ((p = next_prime_digit_number(p)) < limit2) {
        if (is_prime(digit_sum(p)) && is_prime(p)) {
            ++n;
            if (p < limit1)
                printf("%2u: %'u\n", n, p);
            extra_primes[n % last] = p;
        }
    }
    printf("\nLast %d extra primes under %'u:\n", last, limit2);
    for (int i = last - 1; i >= 0; --i)
        printf("%'u: %'u\n", n-i, extra_primes[(n-i) % last]);
    return 0;
}

fn is_prime(n: u64) -> bool {
    primal::is_prime(n)
}

fn next_prime_digit_number(n: u64) -> u64 {
    if n == 0 {
        return 2;
    }
    match n % 10 {
        2 => n + 1,
        3 | 5 => n + 2,
        _ => 2 + next_prime_digit_number(n / 10) * 10,
    }
}

fn digit_sum(mut n: u64) -> u64 {
    let mut sum = 0;
    while n > 0 {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

fn main() {
    let limit1 = 10000;
    let limit2 = 1000000000;
    let last = 10;
    let mut p = 0;
    let mut n = 0;
    let mut extra_primes = vec![0; last];
    println!("Extra primes under {}:", limit1);
    loop {
        p = next_prime_digit_number(p);
        if p >= limit2 {
            break;
        }
        if is_prime(digit_sum(p)) && is_prime(p) {
            n += 1;
            if p < limit1 {
                println!("{:2}: {}", n, p);
            }
            extra_primes[n % last] = p;
        }
    }
    println!("\nLast {} extra primes under {}:", last, limit2);
    let mut i = last;
    while i > 0 {
        i -= 1;
        println!("{}: {}", n - i, extra_primes[(n - i) % last]);
    }
}


FTP

#include <ftplib.h>

int main(void)
{
    netbuf *nbuf;

    FtpInit();
    FtpConnect("kernel.org", &nbuf);
    FtpLogin("anonymous", "", nbuf);
    FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
    FtpChdir("pub/linux/kernel", nbuf);
    FtpDir((void*)0, ".", nbuf);
    FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
    FtpQuit(nbuf);

    return 0;
}

use std::{error::Error, fs::File, io::copy};
use ftp::FtpStream;

fn main() -> Result<(), Box<dyn Error>> {
    let mut ftp = FtpStream::connect("ftp.easynet.fr:21")?;
    ftp.login("anonymous", "")?;
    ftp.cwd("debian")?;
    for file in ftp.list(None)? {
        println!("{}", file);
    }
    let mut stream = ftp.get("README")?;
    let mut file = File::create("README")?;
    copy(&mut stream, &mut file)?;
    Ok(())
}


Fairshare between two and more

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

int turn(int base, int n) {
    int sum = 0;
    while (n != 0) {
        int rem = n % base;
        n = n / base;
        sum += rem;
    }
    return sum % base;
}

void fairshare(int base, int count) {
    int i;

    printf("Base %2d:", base);
    for (i = 0; i < count; i++) {
        int t = turn(base, i);
        printf(" %2d", t);
    }
    printf("\n");
}

void turnCount(int base, int count) {
    int *cnt = calloc(base, sizeof(int));
    int i, minTurn, maxTurn, portion;

    if (NULL == cnt) {
        printf("Failed to allocate space to determine the spread of turns.\n");
        return;
    }

    for (i = 0; i < count; i++) {
        int t = turn(base, i);
        cnt[t]++;
    }

    minTurn = INT_MAX;
    maxTurn = INT_MIN;
    portion = 0;
    for (i = 0; i < base; i++) {
        if (cnt[i] > 0) {
            portion++;
        }
        if (cnt[i] < minTurn) {
            minTurn = cnt[i];
        }
        if (cnt[i] > maxTurn) {
            maxTurn = cnt[i];
        }
    }

    printf("  With %d people: ", base);
    if (0 == minTurn) {
        printf("Only %d have a turn\n", portion);
    } else if (minTurn == maxTurn) {
        printf("%d\n", minTurn);
    } else {
        printf("%d or %d\n", minTurn, maxTurn);
    }

    free(cnt);
}

int main() {
    fairshare(2, 25);
    fairshare(3, 25);
    fairshare(5, 25);
    fairshare(11, 25);

    printf("How many times does each get a turn in 50000 iterations?\n");
    turnCount(191, 50000);
    turnCount(1377, 50000);
    turnCount(49999, 50000);
    turnCount(50000, 50000);
    turnCount(50001, 50000);

    return 0;
}

struct Digits {
    rest: usize,
    base: usize,
}

impl Iterator for Digits {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        if self.rest == 0 {
            return None;
        }
        let (digit, rest) = (self.rest % self.base, self.rest / self.base);
        self.rest = rest;
        Some(digit)
    }
}

fn digits(num: usize, base: usize) -> Digits {
    Digits { rest: num, base: base }
}

struct FairSharing {
    participants: usize,
    index: usize,
}

impl Iterator for FairSharing {
    type Item = usize;
    fn next(&mut self) -> Option<usize> {
        let digit_sum: usize = digits(self.index, self.participants).sum();
        let selected = digit_sum % self.participants;
        self.index += 1;
        Some(selected)
    }
}

fn fair_sharing(participants: usize) -> FairSharing {
    FairSharing { participants: participants, index: 0 }
}

fn main() {
    for i in vec![2, 3, 5, 7] {
        println!("{}: {:?}", i, fair_sharing(i).take(25).collect::<Vec<usize>>());
    }
}


Farey sequence

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

void farey(int n)
{
	typedef struct { int d, n; } frac;
	frac f1 = {0, 1}, f2 = {1, n}, t;
	int k;

	printf("%d/%d %d/%d", 0, 1, 1, n);
	while (f2.n > 1) {
		k = (n + f1.n) / f2.n;
		t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };
		printf(" %d/%d", f2.d, f2.n);
	}

	putchar('\n');
}

typedef unsigned long long ull;
ull *cache;
size_t ccap;

ull farey_len(int n)
{
	if (n >= ccap) {
		size_t old = ccap;
		if (!ccap) ccap = 16;
		while (ccap <= n) ccap *= 2;
		cache = realloc(cache, sizeof(ull) * ccap);
		memset(cache + old, 0, sizeof(ull) * (ccap - old));
	} else if (cache[n])
		return cache[n];

	ull len = (ull)n*(n + 3) / 2;
	int p, q = 0;
	for (p = 2; p <= n; p = q) {
		q = n/(n/p) + 1;
		len -= farey_len(n/p) * (q - p);
	}

	cache[n] = len;
	return len;
}

int main(void)
{
	int n;
	for (n = 1; n <= 11; n++) {
		printf("%d: ", n);
		farey(n);
	}

	for (n = 100; n <= 1000; n += 100)
		printf("%d: %llu items\n", n, farey_len(n));

	n = 10000000;
	printf("\n%d: %llu items\n", n, farey_len(n));
	return 0;
}

#[derive(Copy, Clone)]
struct Fraction {
    numerator: u32,
    denominator: u32,
}

use std::fmt;

impl fmt::Display for Fraction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.numerator, self.denominator)
    }
}

impl Fraction {
    fn new(n: u32, d: u32) -> Fraction {
        Fraction {
            numerator: n,
            denominator: d,
        }
    }
}

fn farey_sequence(n: u32) -> impl std::iter::Iterator<Item = Fraction> {
    let mut a = 0;
    let mut b = 1;
    let mut c = 1;
    let mut d = n;
    std::iter::from_fn(move || {
        if a > n {
            return None;
        }
        let result = Fraction::new(a, b);
        let k = (n + b) / d;
        let next_c = k * c - a;
        let next_d = k * d - b;
        a = c;
        b = d;
        c = next_c;
        d = next_d;
        Some(result)
    })
}

fn main() {
    for n in 1..=11 {
        print!("{}:", n);
        for f in farey_sequence(n) {
            print!(" {}", f);
        }
        println!();
    }
    for n in (100..=1000).step_by(100) {
        println!("{}: {}", n, farey_sequence(n).count());
    }
}


Fermat numbers

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

void mpz_factors(mpz_t n) {
  int factors = 0;
  mpz_t s, m, p;
  mpz_init(s), mpz_init(m), mpz_init(p);

  mpz_set_ui(m, 3);
  mpz_set(p, n);
  mpz_sqrt(s, p);

  while (mpz_cmp(m, s) < 0) {
    if (mpz_divisible_p(p, m)) {
      gmp_printf("%Zd ", m);
      mpz_fdiv_q(p, p, m);
      mpz_sqrt(s, p);
      factors ++;
    }
    mpz_add_ui(m, m, 2);
  }

  if (factors == 0) printf("PRIME\n");
  else gmp_printf("%Zd\n", p);
}

int main(int argc, char const *argv[]) {
  mpz_t fermat;
  mpz_init_set_ui(fermat, 3);
  printf("F(0) = 3 -> PRIME\n");
  for (unsigned i = 1; i < 10; i ++) {
    mpz_sub_ui(fermat, fermat, 1);
    mpz_mul(fermat, fermat, fermat);
    mpz_add_ui(fermat, fermat, 1);
    gmp_printf("F(%d) = %Zd -> ", i, fermat);
    mpz_factors(fermat);
  }

  return 0;
}

 struct DivisorGen {
    curr: u64,
    last: u64,
}

impl Iterator for DivisorGen {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.curr += 2u64;

        if self.curr < self.last{
            None
        } else {
            Some(self.curr)
        }
    }
}

fn divisor_gen(num : u64) -> DivisorGen {
    DivisorGen { curr: 0u64, last: (num / 2u64) + 1u64 }
}

fn is_prime(num : u64) -> bool{
    if num == 2 || num == 3 {
        return true;
    } else if num % 2 == 0 || num % 3 == 0 || num <= 1{
        return false;
    }else{
        for i in divisor_gen(num){
            if num % i == 0{
                return false;
            }
        }
    }
    return true;
}

fn main() {
    let fermat_closure = |i : u32| -> u64 {2u64.pow(2u32.pow(i + 1u32))};
    let mut f_numbers : Vec<u64> = Vec::new();

    println!("First 4 Fermat numbers:");
    for i in 0..4 {
        let f = fermat_closure(i) + 1u64;
        f_numbers.push(f);
        println!("F{}: {}", i, f);
    }

    println!("Factor of the first four numbers:");
    for f in f_numbers.iter(){
        let is_prime : bool = f % 4 == 1 && is_prime(*f);
        let not_or_not = if is_prime {" "} else {" not "};
        println!("{} is{}prime", f, not_or_not);
    }
}


Fibonacci word_fractal

#include <stdio.h>

int main(void)
{
	puts(	"%!PS-Adobe-3.0 EPSF\n"
		"%%BoundingBox: -10 -10 400 565\n"
		"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n"
		"/b{a 90 rotate}def");

	char i;
	for (i = 'c'; i <= 'z'; i++)
		printf("/%c{%c %c}def\n", i, i-1, i-2);

	puts("0 setlinewidth z showpage\n%%EOF");

	return 0;
}

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

fn fibonacci_word(n: usize) -> Vec<u8> {
    let mut f0 = vec![1];
    let mut f1 = vec![0];
    if n == 0 {
        return f0;
    } else if n == 1 {
        return f1;
    }
    let mut i = 2;
    loop {
        let mut f = Vec::with_capacity(f1.len() + f0.len());
        f.extend(&f1);
        f.extend(f0);
        if i == n {
            return f;
        }
        f0 = f1;
        f1 = f;
        i += 1;
    }
}

struct FibwordFractal {
    current_x: f64,
    current_y: f64,
    current_angle: i32,
    line_length: f64,
    max_x: f64,
    max_y: f64,
}

impl FibwordFractal {
    fn new(x: f64, y: f64, length: f64, angle: i32) -> FibwordFractal {
        FibwordFractal {
            current_x: x,
            current_y: y,
            current_angle: angle,
            line_length: length,
            max_x: 0.0,
            max_y: 0.0,
        }
    }
    fn execute(&mut self, n: usize) -> Path {
        let mut data = Data::new().move_to((self.current_x, self.current_y));
        for (i, byte) in fibonacci_word(n).iter().enumerate() {
            data = self.draw_line(data);
            if *byte == 0u8 {
                self.turn(if i % 2 == 1 { -90 } else { 90 });
            }
        }
        Path::new()
            .set("fill", "none")
            .set("stroke", "black")
            .set("stroke-width", "1")
            .set("d", data)
    }
    fn draw_line(&mut self, data: Data) -> Data {
        let theta = (self.current_angle as f64).to_radians();
        self.current_x += self.line_length * theta.cos();
        self.current_y += self.line_length * theta.sin();
        if self.current_x > self.max_x {
            self.max_x = self.current_x;
        }
        if self.current_y > self.max_y {
            self.max_y = self.current_y;
        }
        data.line_to((self.current_x, self.current_y))
    }
    fn turn(&mut self, angle: i32) {
        self.current_angle = (self.current_angle + angle) % 360;
    }
    fn save(file: &str, order: usize) -> std::io::Result<()> {
        use svg::node::element::Rectangle;
        let x = 5.0;
        let y = 5.0;
        let rect = Rectangle::new()
            .set("width", "100%")
            .set("height", "100%")
            .set("fill", "white");
        let mut ff = FibwordFractal::new(x, y, 1.0, 0);
        let path = ff.execute(order);
        let document = svg::Document::new()
            .set("width", 5 + ff.max_x as usize)
            .set("height", 5 + ff.max_y as usize)
            .add(rect)
            .add(path);
        svg::save(file, &document)
    }
}

fn main() {
    FibwordFractal::save("fibword_fractal.svg", 22).unwrap();
}


File size distribution

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

#define MAXORDER 25

int main(int argC, char* argV[])
{
	char str[MAXORDER],commandString[1000],*startPath;
	long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
	int i,j,len;
	double scale;
	FILE* fp;

	if(argC==1)
		printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
	else{
		if(strchr(argV[1],' ')!=NULL){
		len = strlen(argV[1]);
		startPath = (char*)malloc((len+2)*sizeof(char));
		startPath[0] = '\"';
		startPath[len+1]='\"';
		strncpy(startPath+1,argV[1],len);
		startPath[len+2] = argV[1][len];
		sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
	}

	else if(strlen(argV[1])==1 && argV[1][0]=='.')
		strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");

	else
		sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);

	fp = popen(commandString,"r");

	while(fgets(str,100,fp)!=NULL){
			if(str[0]=='0')
				fileSizeLog[0]++;
			else
				fileSizeLog[strlen(str)]++;
	}

	if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
		for(i=0;i<MAXORDER;i++){
			printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
		}
	}

	else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
		CONSOLE_SCREEN_BUFFER_INFO csbi;
		int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
		if(val)
		{

				max = fileSizeLog[0];

				for(i=1;i<MAXORDER;i++)
					(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;

				(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);

				for(i=0;i<MAXORDER;i++){
					printf("\nSize Order < 10^%2d bytes |",i);
					for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
						printf("%c",219);
					printf("%Ld",fileSizeLog[i]);
				}
		}

	}
	return 0;
	}
}

use std::error::Error;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::{env, fmt, io, time};
use walkdir::{DirEntry, WalkDir};

fn main() -> Result<(), Box<dyn Error>> {
    let start = time::Instant::now();
    let args: Vec<String> = env::args().collect();

    let root = parse_path(&args).expect("not a valid path");
    let dir = WalkDir::new(&root);

    let (files, dirs): (Vec<PathBuf>, Vec<PathBuf>) = {
        let pool = pool(dir).expect("unable to retrieve entries from WalkDir");
        partition_from(pool).expect("unable to partition files from directories")
    };

    let (fs_count, dr_count) = (files.len(), dirs.len());
    let (file_counter, total_size) = file_count(files);

    {
        println!("++ File size distribution for : {} ++\n", &root.display());
        println!("Files @ 0B            : {:4}", file_counter[0]);
        println!("Files > 1B  - 1,023B  : {:4}", file_counter[1]);
        println!("Files > 1KB - 1,023KB : {:4}", file_counter[2]);
        println!("Files > 1MB - 1,023MB : {:4}", file_counter[3]);
        println!("Files > 1GB - 1,023GB : {:4}", file_counter[4]);
        println!("Files > 1TB+          : {:4}\n", file_counter[5]);

        println!("Files encountered: {}", fs_count);
        println!("Directories traversed: {}", dr_count);
        println!(
            "Total size of all files: {}\n",
            Filesize::<Kilobytes>::from(total_size)
        );
    }

    let end = time::Instant::now();
    println!("Run time: {:?}\n", end.duration_since(start));
    Ok(())
}

fn parse_path(args: &[String]) -> Result<&Path, io::Error> {

    match args.len() {
        1 => Ok(Path::new(&args[0])),
        _ => Ok(Path::new(&args[1])),
    }
}

fn pool(dir: WalkDir) -> Result<Vec<DirEntry>, Box<dyn Error>> {

    Ok(dir.into_iter().filter_map(|e| e.ok()).collect())
}

fn partition_from(pool: Vec<DirEntry>) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Box<dyn Error>> {

    Ok(pool
        .into_iter()
        .map(|e| e.into_path())
        .partition(|path| path.is_file()))
}

fn file_count(files: Vec<PathBuf>) -> ([u64; 6], u64) {
    let mut counter: [u64; 6] = [0; 6];
    for file in &files {
        match Filesize::<Bytes>::from(file).bytes {
            0 => counter[0] += 1,
            1..=1_023 => counter[1] += 1,
            1_024..=1_048_575 => counter[2] += 1,
            1_048_576..=1_073_741_823 => counter[3] += 1,
            1_073_741_824..=1_099_511_627_775 => counter[4] += 1,
            1_099_511_627_776..=std::u64::MAX => counter[5] += 1,
        }
    }

    let total_file_size = files
        .iter()
        .fold(0, |acc, file| acc + Filesize::<Bytes>::from(file).bytes);
    (counter, total_file_size)
}

trait SizeUnit: Copy {
    fn singular_name() -> String;
    fn num_byte_in_unit() -> u64;
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Bytes;
impl SizeUnit for Bytes {
    fn singular_name() -> String {
        "B".to_string()
    }
    fn num_byte_in_unit() -> u64 {
        1
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Kilobytes;
impl SizeUnit for Kilobytes {
    fn singular_name() -> String {
        "KB".to_string()
    }
    fn num_byte_in_unit() -> u64 {
        1_024
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Filesize<T: SizeUnit> {
    bytes: u64,
    unit: PhantomData<T>,
}

impl<T> From<u64> for Filesize<T>
where
    T: SizeUnit,
{
    fn from(n: u64) -> Self {
        Filesize {
            bytes: n * T::num_byte_in_unit(),
            unit: PhantomData,
        }
    }
}

impl<T> From<Filesize<T>> for u64
where
    T: SizeUnit,
{
    fn from(fsz: Filesize<T>) -> u64 {
        ((fsz.bytes as f64) / (T::num_byte_in_unit() as f64)) as u64
    }
}

impl<T> fmt::Display for Filesize<T>
where
    T: SizeUnit,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

        let size_val = ((self.bytes as f64) / (T::num_byte_in_unit() as f64)) as u64;

        let name_plural = match size_val {
            1 => "",
            _ => "s",
        };

        write!(
            f,
            "{} {}{}",
            (self.bytes as f64) / (T::num_byte_in_unit() as f64),
            T::singular_name(),
            name_plural
        )
    }
}

impl<T> From<&PathBuf> for Filesize<T>
where
    T: SizeUnit,
{
    fn from(f: &PathBuf) -> Self {
        Filesize {
            bytes: f
                .metadata()
                .expect("error with metadata from pathbuf into filesize")
                .len(),
            unit: PhantomData,
        }
    }
}


Find adjacent primes which differ by a square integer

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

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

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

int issquare( int p ) {
    int i;
    for(i=0;i*i<p;i++);
    return i*i==p;
}

int main(void) {
    int i=3, j=2;
    for(i=3;j<=1000000;i=j) {
        j=nextprime(i);
        if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
    }
    return 0;
}

use prime_tools ;

fn is_square_number( num : u32 ) -> bool {
   let comp_num : f32 = num as f32 ;
   let root = comp_num.sqrt( ) ;
   return root == root.floor( ) ;
}

fn main() {
   let primes: Vec<u32> = prime_tools::get_primes_less_than_x(1000000_u32) ;
   let len = primes.len( ) ;
   let mut i : usize = 0 ;
   while  i < len - 1  {
      let diff : u32 = primes[ i + 1 ] - primes[ i ] ;
      if diff > 36 && is_square_number( diff ) {
         println!("{} - {} = {}" , primes[ i + 1 ] , primes[ i ] , diff) ;
      }
      i += 1 ;
   }
}


Find prime n such that reversed n is also prime

#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 reverse(unsigned int n) {
    unsigned int rev = 0;
    for (; n > 0; n /= 10)
        rev = rev * 10 + n % 10;
    return rev;
}

int main() {
    unsigned int count = 0;
    for (unsigned int n = 1; n < 500; ++n) {
        if (is_prime(n) && is_prime(reverse(n)))
            printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
    }
    printf("\nCount = %u\n", count);
    return 0;
}

use prime_tools ;

fn myreverse( n : u32 ) -> u32 {
   let forward : String = n.to_string( ) ;
   let numberstring = &forward[..] ;
   let mut reversed : String = String::new( ) ;
   for c in numberstring.chars( ).rev( ) {
      reversed.push( c ) ;
   }
   *&reversed[..].parse::<u32>( ).unwrap( )
}

fn main() {
   let mut reversible_primes : Vec<u32> = Vec::new( ) ;
   for num in 2..=500 {
      if prime_tools::is_u32_prime( num ) && prime_tools::is_u32_prime(
               myreverse( num ))  {
            reversible_primes.push( num ) ;
      }
   }
   println!("{:?}" , reversible_primes ) ;
}


Find the last Sunday of each month

use std::env::args;
use time::{Date, Duration};

fn main() {
    let year = args().nth(1).unwrap().parse::<i32>().unwrap();
    (1..=12)
        .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1))
        .filter_map(|date| date.ok())
        .for_each(|date| {
            let days_back =
                Duration::days(((date.weekday().number_from_sunday() as i64 + 5) % 7) + 1);
            println!("{}", date - days_back);
        });
}


Finite state machine

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

int main(int argc, char **argv)
{
  typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;

  typedef struct statechange {
    const int in;
    const State out;
  } statechange;

#define MAXINPUTS 3
  typedef struct FSM {
    const State state;
    void (*Action)(void);
    const statechange table[MAXINPUTS];
  } FSM;

  char str[10];
  void Ready(void)    { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
  void Waiting(void)  { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
  void Refund(void)   { fprintf(stderr, "Please collect refund.\n"); }
  void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
  void Collect(void)  { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
  void Quit(void)     { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }

  const FSM fsm[] = {
    { READY,    &Ready,    {{'D', WAITING},  {'Q', QUIT },    {-1, READY}    }},
    { WAITING,  &Waiting,  {{'S', DISPENSE}, {'R', REFUND},   {-1, WAITING}  }},
    { REFUND,   &Refund,   {{ -1, READY}                                     }},
    { DISPENSE, &Dispense, {{ -1, COLLECT}                                   }},
    { COLLECT,  &Collect,  {{'C', READY},    { -1, COLLECT }                 }},
    { QUIT,     &Quit,     {{ -1, QUIT}                                      }},
  };

  int each;
  State state = READY;

  for (;;) {
    fsm[state].Action();
    each = 0;
    while (!( ((fsm[state].table[each].in == -1)

               || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
    state = fsm[state].table[each].out;
  }

  return 0;
}

enum State {
    Ready,
    Waiting,
    Dispense,
    Refunding,
    Exit,
}

#[methods_enum::gen(Act: run)]
impl State {
    pub fn set(&mut self);
    pub fn input_char(&mut self, ch: char);

    fn run(&mut self, act: Act) {
        match self {
            State::Ready => match act {
                Act::set() => println!("Ready: d - deposit / q - quit "),
                Act::input_char('d') => self.set_state(State::Waiting),
                Act::input_char('q') => self.set_state(State::Exit),
                _ => self.set(),
            },
            State::Waiting => match act {
                Act::set() => println!("Waiting: s - select / r - refund "),
                Act::input_char('s') => self.set_state(State::Dispense),
                Act::input_char('r') => self.set_state(State::Refunding),
                _ => self.set(),
            },
            State::Dispense => match act {
                Act::set() => println!("Dispense: r - remove "),
                Act::input_char('r') => self.set_state(State::Ready),
                _ => self.set(),
            },
            State::Refunding => match act {
                Act::set() => {
                    println!("Refunding: refund of the deposit...");
                    self.set_state(State::Ready)
                }
                _ => (),
            },
            State::Exit => match act {
                Act::set() => println!("Exit: goodbye! "),
                _ => panic!("!! Invalid command for State::Exit: '{act:?}'"),
            },
        }
    }

    fn set_state(&mut self, new_state: State) {
        *self = new_state;
        self.set();
    }
}

fn main() {
    let mut machine = State::Ready;
    machine.set();

    while !matches!(&machine, State::Exit) {
        machine.input_char(char_entered());
    }
}

fn char_entered() -> char {
    let mut text = String::new();
    std::io::stdin().read_line(&mut text).unwrap_or(0);
    text.chars().next().unwrap_or('\x0d')
}


First power of 2 that has leading decimal digits of 12

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

int p(int l, int n) {
    int test = 0;
    double logv = log(2.0) / log(10.0);
    int factor = 1;
    int loop = l;
    while (loop > 10) {
        factor *= 10;
        loop /= 10;
    }
    while (n > 0) {
        int val;

        test++;
        val = (int)(factor * pow(10.0, fmod(test * logv, 1)));
        if (val == l) {
            n--;
        }
    }
    return test;
}

void runTest(int l, int n) {
    printf("p(%d, %d) = %d\n", l, n, p(l, n));
}

int main() {
    runTest(12, 1);
    runTest(12, 2);
    runTest(123, 45);
    runTest(123, 12345);
    runTest(123, 678910);

    return 0;
}

fn power_of_two(l: isize, n: isize) -> isize {
    let mut test: isize = 0;
    let log: f64 = 2.0_f64.ln() / 10.0_f64.ln();
    let mut factor: isize = 1;
    let mut looop = l;
    let mut nn = n;
    while looop > 10 {
        factor *= 10;
        looop /= 10;
    }

    while nn > 0 {
        test = test + 1;
        let val: isize = (factor as f64 * 10.0_f64.powf(test as f64 * log % 1.0)) as isize;

        if val == l {
            nn = nn - 1;
        }
    }

    test
}

fn run_test(l: isize, n: isize) {
    println!("p({}, {}) = {}", l, n, power_of_two(l, n));
}

fn main() {
    run_test(12, 1);
    run_test(12, 2);
    run_test(123, 45);
    run_test(123, 12345);
    run_test(123, 678910);
}


Four is magic

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

typedef struct named_number_tag {
    const char* name;
    uint64_t number;
} named_number;

const named_number named_numbers[] = {
    { "hundred", 100 },
    { "thousand", 1000 },
    { "million", 1000000 },
    { "billion", 1000000000 },
    { "trillion", 1000000000000 },
    { "quadrillion", 1000000000000000ULL },
    { "quintillion", 1000000000000000000ULL }
};

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

size_t append_number_name(GString* str, uint64_t n) {
    static const char* small[] = {
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen"
    };
    static const char* tens[] = {
        "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
    };
    size_t len = str->len;
    if (n < 20) {
        g_string_append(str, small[n]);
    }
    else if (n < 100) {
        g_string_append(str, tens[n/10 - 2]);
        if (n % 10 != 0) {
            g_string_append_c(str, '-');
            g_string_append(str, small[n % 10]);
        }
    } else {
        const named_number* num = get_named_number(n);
        uint64_t p = num->number;
        append_number_name(str, n/p);
        g_string_append_c(str, ' ');
        g_string_append(str, num->name);
        if (n % p != 0) {
            g_string_append_c(str, ' ');
            append_number_name(str, n % p);
        }
    }
    return str->len - len;
}

GString* magic(uint64_t n) {
    GString* str = g_string_new(NULL);
    for (unsigned int i = 0; ; ++i) {
        size_t count = append_number_name(str, n);
        if (i == 0)
            str->str[0] = g_ascii_toupper(str->str[0]);
        if (n == 4) {
            g_string_append(str, " is magic.");
            break;
        }
        g_string_append(str, " is ");
        append_number_name(str, count);
        g_string_append(str, ", ");
        n = count;
    }
    return str;
}

void test_magic(uint64_t n) {
    GString* str = magic(n);
    printf("%s\n", str->str);
    g_string_free(str, TRUE);
}

int main() {
    test_magic(5);
    test_magic(13);
    test_magic(78);
    test_magic(797);
    test_magic(2739);
    test_magic(4000);
    test_magic(7893);
    test_magic(93497412);
    test_magic(2673497412U);
    test_magic(10344658531277200972ULL);
    return 0;
}

fn main() {
    magic(4);
    magic(2_340);
    magic(765_000);
    magic(27_000_001);
    magic(999_123_090);
    magic(239_579_832_723_441);
    magic(std::u64::MAX);
}

fn magic(num: u64) {
    if num == 4 {
        println!("four is magic!");
        println!();
        return;
    }
    let name = number_name(num);
    let len = name.len() as u64;
    print!("{} is {}, ", name, number_name(len));
    magic(len);
}

const LOW: &'static [&'static str] = &[
    "zero", "one", "two", "three", "four", "five",
    "six", "seven", "eight","nine", "ten",
    "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen"
];
const MED: &'static [&'static str] = &[
    "twenty", "thirty", "forty", "fifty",
    "sixy", "seventy", "eighty", "ninety"
];
const HIGH: &'static [&'static str] = &[
    "thousand", "million", "billion",
    "trillion", "quadrillion", "quintillion"
];

fn number_name(num: u64) -> String {
    if num < 20 {
        return LOW[num as usize].to_string();
    }
    if num < 100 {
        let index = ((num / 10) - 2) as usize;
        let tens = MED[index].to_string();
        let remainder = num % 10;
        if remainder > 0 {
            return format!("{}-{}", tens, number_name(remainder));
        }
        return tens;
    }
    if num < 1000 {
        let hundreds = LOW[(num / 100) as usize];
        let remainder = num % 100;
        if remainder > 0 {
            return format!("{} hundred {}", hundreds, number_name(remainder));
        }
        return format!("{} hundred", hundreds);
    }

    let mut remainder = num % 1000;
    let mut cur = if remainder > 0 { number_name(remainder) } else { "".to_string() };
    let mut n = num / 1000;

    for noun in HIGH.iter() {
        if n > 0 {
            remainder = n % 1000;
            if remainder > 0 {

                cur =
                    if cur.len() > 0 { format!("{} {} {}", number_name(remainder), noun, cur ) }
                    else { format!("{} {}", number_name(remainder), noun) }
            }
            n /= 1000;
        }
    }
    return cur;
}